Skip to content

Instantly share code, notes, and snippets.

@zenatureza
Created January 31, 2021 03:18
Show Gist options
  • Save zenatureza/36ea750eff86b46a25c22c9c43c08f38 to your computer and use it in GitHub Desktop.
Save zenatureza/36ea750eff86b46a25c22c9c43c08f38 to your computer and use it in GitHub Desktop.
schema
import { Router } from 'express';
import OrdersController from '../controllers/OrdersController';
import { celebrate, Segments, Joi } from 'celebrate';
const ordersRouter = Router();
const ordersController = new OrdersController();
ordersRouter.get('/:id?', ordersController.index);
ordersRouter.post(
'/',
celebrate({
[Segments.BODY]: Joi.object().keys({
products: Joi.array().items(
Joi.object({
name: Joi.string().error(new Error('Products must have a name')),
quantity: Joi.number().error(
new Error('Products must have a quantity'),
),
}),
),
}),
}),
ordersController.create,
);
export default ordersRouter;
import 'reflect-metadata';
import 'dotenv/config';
import express, { Request, Response, NextFunction } from 'express';
import 'express-async-errors';
import routes from './routes';
import AppError from '@shared/errors/AppError';
import { errors } from 'celebrate';
import '@shared/infra/typeorm';
import '@shared/container';
const app = express();
app.use(express.json());
app.use(routes);
app.use(errors());
app.use((err: Error, request: Request, response: Response, _: NextFunction) => {
if (err instanceof AppError) {
const { statusCode, message } = err;
return response.status(statusCode).json({
status: 'error',
message,
});
}
console.error(err);
return response.status(500).json({
status: 'error',
message: 'Internal server error',
});
});
app.listen(3000, () => {
console.log('🌴 starting again node server on port 3000...');
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment