BETTERZON-93: Adding API endpoint to get managed shops (#47)

This commit is contained in:
Patrick 2021-05-16 12:28:11 +02:00 committed by GitHub
parent cb55cae692
commit b185e4e5e3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 49 additions and 3 deletions

View File

@ -6,6 +6,7 @@ import express, {Request, Response} from 'express';
import * as VendorService from './vendors.service';
import {Vendor} from './vendor.interface';
import {Vendors} from './vendors.interface';
import * as UserService from '../users/users.service';
/**
@ -19,7 +20,7 @@ export const vendorsRouter = express.Router();
* Controller Definitions
*/
// GET items/
// GET vendors/
vendorsRouter.get('/', async (req: Request, res: Response) => {
try {
const vendors: Vendors = await VendorService.findAll();
@ -31,7 +32,24 @@ vendorsRouter.get('/', async (req: Request, res: Response) => {
}
});
// GET items/:id
// GET vendors/managed
vendorsRouter.get('/managed', async (req: Request, res: Response) => {
console.log('here');
try {
// Authenticate user
const user_ip = req.connection.remoteAddress ?? '';
const user = await UserService.checkSessionWithCookie(req.cookies.betterauth, user_ip);
const vendors = await VendorService.getManagedShops(user.user_id);
res.status(200).send(vendors);
} catch (e) {
console.log('Error handling a request: ' + e.message);
res.status(500).send(JSON.stringify({'message': 'Internal Server Error. Try again later.'}));
}
});
// GET vendors/:id
vendorsRouter.get('/:id', async (req: Request, res: Response) => {
const id: number = parseInt(req.params.id, 10);
@ -50,7 +68,7 @@ vendorsRouter.get('/:id', async (req: Request, res: Response) => {
}
});
// GET items/:name
// GET vendors/search/:term
vendorsRouter.get('/search/:term', async (req: Request, res: Response) => {
const term: string = req.params.term;

View File

@ -17,6 +17,7 @@ const pool = mariadb.createPool({
import {Vendor} from './vendor.interface';
import {Vendors} from './vendors.interface';
import {User} from '../users/user.interface';
/**
@ -123,3 +124,30 @@ export const findBySearchTerm = async (term: string): Promise<Vendors> => {
return vendorRows;
};
/**
* Get all vendors that have the given user as admin
* @param user The user to return the managed shops for
*/
export const getManagedShops = async (user_id: number): Promise<Vendors> => {
let conn;
let vendorRows = [];
try {
conn = await pool.getConnection();
const rows = await conn.query('SELECT vendor_id, name, streetname, zip_code, city, country_code, phone, website FROM vendors WHERE admin_id LIKE ?', user_id);
for (let row in rows) {
if (row !== 'meta') {
vendorRows.push(rows[row]);
}
}
} catch (err) {
throw err;
} finally {
if (conn) {
conn.end();
}
}
return vendorRows;
};