Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

wrap middleware #324

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion .nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
18
20
20 changes: 8 additions & 12 deletions docs/docs/the-basics/coding-with-practica.md
Original file line number Diff line number Diff line change
Expand Up @@ -135,18 +135,14 @@ This is a very typical express code, if you're familiar with express you'll be p

```javascript
// A new route to edit order
router.put('/:id', async (req, res, next) => {
try {
logger.info(`Order API was called to edit order ${req.params.id}`);
// Later on we will call the main code in the domain layer
// Fow now let's put hard coded values
res.json({id:1, userId: 1, productId: 2, countryId: 1,
deliveryAddress: '123 Main St, New York',
paymentTermsInDays: 30}).status(200).end();
} catch (err) {
next(err);
}
});
router.put('/:id', wrapHandler(async (req, res, next) => {
logger.info(`Order API was called to edit order ${req.params.id}`);
// Later on we will call the main code in the domain layer
// Fow now let's put hard coded values
res.json({id:1, userId: 1, productId: 2, countryId: 1,
deliveryAddress: '123 Main St, New York',
paymentTermsInDays: 30}).status(200).end();
}));
```

> **✅Best practice:** The API entry-point (controller) should stay thin and focus on forwarding the request to the domain layer.
Expand Down
2 changes: 1 addition & 1 deletion src/code-templates/.nvmrc
Original file line number Diff line number Diff line change
@@ -1 +1 @@
18
20
2 changes: 1 addition & 1 deletion src/code-templates/libraries/logger/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { context } from '@practica/request-context';
import { context } from '@practica/middlewares';
import { Logger, LoggerConfiguration } from './definition';
import PinoLogger from './pino.logger';

Expand Down
2 changes: 1 addition & 1 deletion src/code-templates/libraries/logger/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@
"url": "git+https://github.com/practicajs/practica.git"
},
"dependencies": {
"@practica/request-context": "^0.1.0",
"@practica/middlewares": "^0.1.0",
"@practica/configuration-provider": "^0.0.1-alpha.1",
"pino": "^8.5.0"
},
Expand Down
2 changes: 1 addition & 1 deletion src/code-templates/libraries/logger/test/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import sinon from 'sinon';
import { context } from '@practica/request-context';
import { context } from '@practica/middlewares';
import { logger } from '../index';

describe('logger', () => {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,2 +1,3 @@
export { context } from './src/context';
export { addRequestId as addRequestIdExpressMiddleware } from './src/request-id/express/middleware';
export * from './src/wrap-handler';

Check failure on line 3 in src/code-templates/libraries/middlewares/index.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

Insert `⏎`

Check failure on line 3 in src/code-templates/libraries/middlewares/index.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

Insert `⏎`

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"name": "@practica/request-context",
"name": "@practica/middlewares",
"version": "0.1.0",
"description": "",
"main": ".dist/index.js",
Expand Down
File renamed without changes.
12 changes: 12 additions & 0 deletions src/code-templates/libraries/middlewares/src/wrap-handler.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@

Check failure on line 1 in src/code-templates/libraries/middlewares/src/wrap-handler.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

Replace `⏎import·express·from·"express"` with `import·express·from·'express'`

Check failure on line 1 in src/code-templates/libraries/middlewares/src/wrap-handler.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

Replace `⏎import·express·from·"express"` with `import·express·from·'express'`
import express from "express";

Check failure on line 2 in src/code-templates/libraries/middlewares/src/wrap-handler.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

'express' should be listed in the project's dependencies, not devDependencies

Check failure on line 2 in src/code-templates/libraries/middlewares/src/wrap-handler.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

'express' should be listed in the project's dependencies, not devDependencies

export function wrapHandler(handler: express.Handler) {
return async (req: express.Request, res: express.Response, next: express.NextFunction) => {

Check failure on line 5 in src/code-templates/libraries/middlewares/src/wrap-handler.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

Replace `req:·express.Request,·res:·express.Response,·next:·express.NextFunction` with `⏎····req:·express.Request,⏎····res:·express.Response,⏎····next:·express.NextFunction⏎··`

Check failure on line 5 in src/code-templates/libraries/middlewares/src/wrap-handler.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

Replace `req:·express.Request,·res:·express.Response,·next:·express.NextFunction` with `⏎····req:·express.Request,⏎····res:·express.Response,⏎····next:·express.NextFunction⏎··`
try {
await handler(req, res, next);
} catch (error) {
next(error);
}
};
}

Check failure on line 12 in src/code-templates/libraries/middlewares/src/wrap-handler.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

Insert `⏎`

Check failure on line 12 in src/code-templates/libraries/middlewares/src/wrap-handler.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

Insert `⏎`
78 changes: 50 additions & 28 deletions src/code-templates/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
Expand Up @@ -2,49 +2,41 @@
import express from 'express';
import { logger } from '@practica/logger';
import * as newOrderUseCase from '../../domain/new-order-use-case';
import { wrapHandler } from '@practica/middlewares';

Check failure on line 5 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

`@practica/middlewares` import should occur before import of `../../domain/new-order-use-case`

Check failure on line 5 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

`@practica/middlewares` import should occur before import of `../../domain/new-order-use-case`

export default function defineRoutes(expressApp: express.Application) {
const router = express.Router();

router.post('/', async (req, res, next) => {
try {
logger.info(
`Order API was called to add new Order ${util.inspect(req.body)}`
);
// ✅ Best Practice: Using the 3-tier architecture, routes/controller are kept thin, logic is encapsulated in a dedicated domain folder
const addOrderResponse = await newOrderUseCase.addOrder(req.body);
return res.json(addOrderResponse);
} catch (error) {
next(error);
return undefined;
}
});
router.post('/', wrapHandler(async (req, res, next) => {

Check failure on line 10 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

Replace `'/',` with `⏎····'/',⏎···`

Check warning on line 10 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

'next' is defined but never used

Check failure on line 10 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

Replace `'/',` with `⏎····'/',⏎···`

Check warning on line 10 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

'next' is defined but never used
logger.info(

Check failure on line 11 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

Replace `····` with `······`

Check failure on line 11 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

Replace `····` with `······`
`Order API was called to add new Order ${util.inspect(req.body)}`

Check failure on line 12 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

Insert `··`

Check failure on line 12 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

Insert `··`
);

Check failure on line 13 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

Insert `··`

Check failure on line 13 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

Insert `··`
// ✅ Best Practice: Using the 3-tier architecture, routes/controller are kept thin, logic is encapsulated in a dedicated domain folder
const addOrderResponse = await newOrderUseCase.addOrder(req.body);
res.json(addOrderResponse);
}));

// get existing order by id
router.get('/:id', async (req, res, next) => {
try {
logger.info(`Order API was called to get user by id ${req.params.id}`);
const response = await newOrderUseCase.getOrder(
parseInt(req.params.id, 10)
);

if (!response) {
res.status(404).end();
return;
}
router.get('/:id', wrapHandler(async (req, res, next) => {

Check warning on line 20 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (16.x, ubuntu-latest)

'next' is defined but never used

Check warning on line 20 in src/code-templates/services/order-service/entry-points/api/routes.ts

View workflow job for this annotation

GitHub Actions / build (18.x, ubuntu-latest)

'next' is defined but never used
logger.info(`Order API was called to get user by id ${req.params.id}`);
const response = await newOrderUseCase.getOrder(
parseInt(req.params.id, 10)
);

res.json(response);
} catch (error) {
next(error);
if (!response) {
res.status(404).end();
return;
}
});

res.json(response);
}));

// delete order by id
router.delete('/:id', async (req, res) => {
router.delete('/:id', wrapHandler(async (req, res) => {
logger.info(`Order API was called to delete order ${req.params.id}`);
await newOrderUseCase.deleteOrder(parseInt(req.params.id, 10));
res.status(204).end();
});
}));

expressApp.use('/order', router);
}
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import helmet from 'helmet';
import { errorHandler } from '@practica/error-handling';
import * as configurationProvider from '@practica/configuration-provider';
import { jwtVerifierMiddleware } from '@practica/jwt-token-verifier';
import { addRequestIdExpressMiddleware } from '@practica/request-context';
import { addRequestIdExpressMiddleware } from '@practica/middlewares';
import configurationSchema from '../../config';
import defineRoutes from './routes';

Expand Down
8 changes: 4 additions & 4 deletions src/code-templates/services/order-service/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
"@practica/error-handling": "^0.0.3",
"@practica/jwt-token-verifier": "^0.0.2",
"@practica/logger": "^0.0.3",
"@practica/request-context": "^0.1.0",
"@practica/middlewares": "^0.1.0",
"@practica/validation": "^0.0.3",
"@prisma/client": "^4.6.1",
"@sinclair/typebox": "^0.23.5",
Expand All @@ -33,9 +33,9 @@
"axios": "^0.26.1",
"express": "^4.17.3",
"helmet": "^6.0.0",
"sequelize": "^6.17.0",
"node-notifier": "^10.0.1",
"pg": "^8.7.3"
"pg": "^8.7.3",
"sequelize": "^6.17.0"
},
"devDependencies": {
"@jest-performance-reporter/core": "^2.1.2",
Expand All @@ -48,7 +48,7 @@
"@types/pg": "^8.6.5",
"@types/sequelize": "^4.28.11",
"@types/sinon": "^10.0.11",
"docker-compose": "^0.23.17",
"docker-compose": "^0.24.7",
"is-ci": "^3.0.1",
"is-port-reachable": "^3.0.0",
"jest": "^27.5.1",
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import isPortReachable from 'is-port-reachable';
import path from 'path';
import dockerCompose from 'docker-compose';
import { v2 as dockerCompose } from 'docker-compose'
import { execSync } from 'child_process';

export default async () => {
Expand Down
Loading