More Related Content Similar to express.pdf (20) More from NuttavutThongjor1 (20) express.pdf2. Babel Coder
RESTFUL
• Stands for “Representational State Transfer”
• RESTful Web Services are one way of providing interoperability between computer systems on
the Internet.
11. Babel Coder
HTTP STATUS CODES
CODE STATUS
1xx Informational responses
2xx Success
3xx Redirection
4xx Client Errors
5xx Server Errors
12. Babel Coder
HTTP STATUS CODES
CODE STATUS
200 OK
201 Created
204 No Content
401 Unauthorized
404 Not Found
405 Method Not Allowed
422 Unprocessable Entity
500 Internal Server Error
15. Babel Coder
EXPRESS
import express from 'express'
const app = express()
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(3000, () =>
console.log(`App listening on http://0.0.0.0:3000`)
)
16. Babel Coder
MIDDLEWARE
app = express()
app.use(function (req, res, next) {
console.log('Time:', Date.now())
next()
})
app.use(function (err, req, res, next) {
console.error(err.stack)
res.status(500).send('Something broke!')
})
17. Babel Coder
ROUTE-LEVEL MIDDLEWARE
const app = express()
const router = express.Router()
router.get(
'/', (req, res) => res.send('Articles')
)
router.post(
'/', (req, res) => res.send(req.body.title)
)
app.use('/articles', router)
GET /articles
POST /articles
import bodyParser from 'body-parser'
app.use(bodyParser.json())
19. Babel Coder
BODY VALIDATOR
const bodyValidator =
<T extends Type<object>>(Dto: T): RequestHandler =>
async (req, _res, next) => {
const dto = plainToInstance(Dto, req.body, { strategy: 'excludeAll' });
const errors = await validate(dto);
if (errors.length > 0) return next(new ValidationError(errors));
req.body = dto;
next();
};
export const register: RequestHandler[] = [
bodyValidator(SignUpFormDto),
authenticator.signUp,
async (req, res) => {
res.status(HTTP_STATUSES.CREATED).json(new UserResponseDto(req.user));
},
];
export class SignUpFormDto {
@Expose()
@IsEmail()
email: string;
@Expose()
@Length(8)
password: string;
@Expose()
name: string;
}
import { ValidationError as Err } from 'class-validator';
export class ValidationError extends Error {
constructor(public errors: Err[]) {
super('Validation Error');
}
}
20. Babel Coder
RESPONSE TRANSFORMER
const responseTransformer: RequestHandler = (_req, res, next) => {
const oldJson = res.json;
res.json = (body) => {
if ('errors' in body) return oldJson.call(res, body);
return oldJson.call(
res,
instanceToPlain(body, {
strategy: 'excludeAll',
})
);
};
next();
};
export class UserResponseDto {
@Expose()
name: string;
@Expose()
email: string;
@Expose()
avatar: string;
@Expose()
role: Role;
constructor(user: User) {
Object.assign(this, user);
}
}
21. Babel Coder
ERROR HANDLER
const errorHandler: ErrorRequestHandler = (err, _req, res, next) => {
if (err instanceof ValidationError) {
res.status(HTTP_STATUSES.BAD_REQUEST).json({ errors: err.errors });
}
if (err instanceof QueryFailedError) {
res.status(HTTP_STATUSES.BAD_REQUEST).json({ errors: err.message });
}
next(err);
};