Skip to content

Commit

Permalink
add delete api to external api
Browse files Browse the repository at this point in the history
  • Loading branch information
goemen committed May 3, 2024
1 parent d21c422 commit 2569cfb
Show file tree
Hide file tree
Showing 7 changed files with 115 additions and 37 deletions.
18 changes: 1 addition & 17 deletions backend-external/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,29 +80,13 @@ app.use(/(\/api)?/, apiRouter);
apiRouter.get('/', (_req, res) => {
res.sendStatus(200); // generally for route verification and health check.
});
const globalMiddleware = (req: Request, res: Response, next: NextFunction) => {
const apiKey = req.header('x-api-key');
if (apiKey) {
if (config.get('server:apiKey') === apiKey) {
next();
} else {
logger.error('Invalid API Key');
res.status(401).send({ message: 'Invalid API Key' });
}
} else {
logger.error('API Key is missing in the request header');
res.status(400).send({
message: 'API Key is missing in the request header',
});
}
};

const specs = swaggerJsdoc(utils.swaggerDocsOptions);
apiRouter.use(
'/v1/docs',
swaggerUi.serve,
swaggerUi.setup(specs, { explorer: true }),
);
apiRouter.use(globalMiddleware);
apiRouter.use('/v1/pay-transparency', payTransparencyRouter);
// Handle 500

Expand Down
12 changes: 8 additions & 4 deletions backend-external/src/config/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,17 +10,21 @@ config.defaults({
logLevel: process.env.LOG_LEVEL,
morganFormat: 'dev',
apiKey: process.env.EXTERNAL_CONSUMER_API_KEY || 'api-key',
deleteReportsApiKey:
process.env.EXTERNAL_API_DELETE_REPORTS_KEY || 'api-key',
port: process.env.PORT || 3002,
rateLimit: {
enabled: process.env.IS_RATE_LIMIT_ENABLED || false, // Disable if rate limiting is not required
windowMs: process.env.RATE_LIMIT_WINDOW_MS || 60000, // 1 minute
limit: process.env.RATE_LIMIT_LIMIT || 100, // Limit each IP to 100 requests per `window` (here, per 1 minute)
},
baseURL: process.env.BASE_URL || 'http://localhost:3002'
baseURL: process.env.BASE_URL || 'http://localhost:3002',
},
backend:{
backend: {
apiKey: process.env.BACKEND_EXTERNAL_API_KEY || 'api-key',
url: process.env.BACKEND_URL || 'http://localhost:3010'
}
deleteReportsApiKey:
process.env.BACKEND_EXTERNAL_DELETE_REPORTS_API_KEY || 'api-key',
url: process.env.BACKEND_URL || 'http://localhost:3010',
},
});
export { config };
70 changes: 68 additions & 2 deletions backend-external/src/v1/routes/pay-transparency-routes.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,28 @@
import express, { Request, Response } from 'express';
import express, { NextFunction, Request, Response } from 'express';
import { payTransparencyService } from '../services/pay-transparency-service';
import { utils } from '../../utils';
import { logger } from '../../logger';
import { config } from '../../config';

const router = express.Router();
const validateApiKey =
(validKey: string) => (req: Request, res: Response, next: NextFunction) => {
const apiKey = req.header('x-api-key');
if (apiKey) {
if (validKey === apiKey) {
next();
} else {
logger.error('Invalid API Key');
res.status(401).send({ message: 'Invalid API Key' });
}
} else {
logger.error('API Key is missing in the request header');
res.status(400).send({
message: 'API Key is missing in the request header',
});
}
};

/**
* @swagger
* components:
Expand Down Expand Up @@ -71,7 +91,7 @@ const router = express.Router();
* items:
* $ref: "#/components/schemas/CalculatedData"
* Report:
* allOf:
* allOf:
* - $ref: "#/components/schemas/ReportItem"
*
* PaginatedReports:
Expand Down Expand Up @@ -139,6 +159,7 @@ const router = express.Router();
*/
router.get(
'/',
validateApiKey(config.get('server:apiKey')),
utils.asyncHandler(async (req: Request, res: Response) => {
try {
const startDate = req.query.startDate?.toString();
Expand All @@ -165,4 +186,49 @@ router.get(
}
}),
);

/**
* @swagger
* tags:
* name: Reports
* /delete-reports:
* delete:
* summary: Delete reports
* tags: [Reports]
* security:
* - ApiKeyAuth: []
* parameters:
* - in: query
* name: companyId
* required: true
* schema:
* type: string
* responses:
* 200:
* description: Successfully deleted reports
* content:
* application/json:
* schema:
* type: object
* properties:
* message:
* type: string
*/
router.delete(
'/delete-reports',
validateApiKey(config.get('server:deleteReportsApiKey')),
async (req, res) => {
try {
const { data } = await payTransparencyService.deleteReports(req);
if (data.error) {
return res.status(400).json({ message: data.message });
}

return res.status(200).json({ message: data.message });
} catch (error) {
return res.status(500).json({ message: error.message });
}
},
);

export default router;
33 changes: 28 additions & 5 deletions backend-external/src/v1/services/pay-transparency-service.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,39 @@
import { AxiosRequestConfig } from 'axios';
import { utils } from '../../utils';
import { config } from '../../config';
import { Request } from 'express';

export const payTransparencyService = {
async getPayTransparencyData(startDate: string, endDate: string, offset: number, limit: number) {
async getPayTransparencyData(
startDate: string,
endDate: string,
offset: number,
limit: number,
) {
const axiosConfig = {
params: {
startDate,
endDate,
offset,
limit
}
limit,
},
};
const { status, data } = await utils.backendAxios().get('/external-consumer-api/v1/', axiosConfig);
const { status, data } = await utils
.backendAxios()
.get('/external-consumer-api/v1/', axiosConfig);
return { status, data };
}
},
async deleteReports(req: Request) {
const axiosConfig: AxiosRequestConfig = {
params: req.params,
headers: {
'x-api-key': config.get('backend:deleteReportsApiKey'),
},
};
const { status, data } = await utils.backendAxios().delete<{
error: boolean;
message: string;
}>('/external-consumer-api/v1/delete-reports', axiosConfig);
return { status, data };
},
};
14 changes: 6 additions & 8 deletions backend/src/v1/routes/external-consumer-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { externalConsumerService } from '../services/external-consumer-service';
import { utils } from '../services/utils-service';
import { logger } from '../../logger';
import { config } from '../../config';
import passport from 'passport';
import { auth } from '../services/auth-service';

const validateToken =
(validApiKey: string) =>
Expand Down Expand Up @@ -54,14 +52,14 @@ router.get(

router.delete(
'/delete-reports',
validateToken(config.get('backendExternal:apiDeleteReportsKey')),
passport.authenticate('jwt', { session: false }),
(req: Request, res: Response, next: NextFunction) => {
auth.isValidBackendToken()(req, res, next);
},
async (req, res) => {
const { bceid_business_guid } = utils.getSessionUser(req)?._json;

try {
await externalConsumerService.deleteReports(req.query.companyId as string);
res.status(200).json({ error: false, message: 'Reports deleted' });
} catch (error) {
res.json({ error: true, message: error.message });
}
},
);

Expand Down
1 change: 1 addition & 0 deletions backend/src/v1/services/auth-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,7 @@ const auth = {
}
const userInfoFrontend = {
displayName: userInfo._json.display_name,
businessId: userInfo._json.bceid_business_guid,
...session.companyDetails,
};
return res.status(HttpStatus.OK).json(userInfoFrontend);
Expand Down
4 changes: 3 additions & 1 deletion backend/src/v1/services/external-consumer-service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,9 @@ const externalConsumerService = {

await tx.pay_transparency_report.deleteMany({
where: {
pay_transparency_company: {},
pay_transparency_company: {
bceid_business_guid,
},
},
});
});
Expand Down

0 comments on commit 2569cfb

Please sign in to comment.