Les dejo el código de order.model, orders.router, order.schema y order.service:
.
order.model
.
const ORDER_TABLE = 'orders';
const OrderSchema = {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER,
},
customerId: {
field: 'customer_id',
allowNull: false,
type: DataTypes.INTEGER,
References: {
model: CUSTOMER_TABLE,
key: 'id',
},
onUpdate: 'CASCADE',
onDelete: 'SET NULL',
},
createdAt: {
allowNull: false,
type: DataTypes.DATE,
field: 'created_at',
defaultValue: Sequelize.NOW,
},
};
class Order extends Model {
static associate(models) {
this.belongsTo(models.Customer, {
as: 'customer',
});
}
static config(sequelize) {
return {
sequelize,
tableName: ORDER_TABLE,
modelName: 'Order',
timestamps: false,
};
}
}
module.exports = { Order, OrderSchema, ORDER_TABLE };
.
orders.router
.
const express = require('express');
const OrderService = require('../services/order.service');
const validatorHandler = require('../middlewares/validator.handler');
const {
getOrderSchema,
createOrderSchema,
} = require('../schemas/order.schema');
const router = express.Router();
const service = new OrderService();
router.get(
'/:id',
validatorHandler(getOrderSchema, 'params'),
async (req, res, next) => {
try {
const { id } = req.params;
const order = await service.findOne(id);
res.json(order);
} catch (error) {
next(error);
}
}
);
router.post(
'/',
validatorHandler(createOrderSchema, 'body'),
async (req, res, next) => {
try {
const body = req.body;
const newOrder = await service.create(body);
res.status(201).json({ newOrder });
} catch (error) {
next(error);
}
}
);
module.exports = router;
.
order.service
.
const boom = require('@hapi/boom');
const { models } = require('./../libs/sequelize');
class OrderService {
constructor() {
}
async create(data) {
const newOrder = await models.Order.create(data);
return newOrder;
}
async find() {
return [];
}
async findOne(id) {
const order = await models.Order.findByPk(id, {
include: [
{
association: 'customer',
include: ['user'],
},
],
});
return order;
}
async update(id, changes) {
return {
id,
changes,
};
}
async delete(id) {
return { id };
}
}
module.exports = OrderService;
.
order.schema
.
const Joi = require('joi');
const id = Joi.number().integer()
const customerId = Joi.number().integer();
const getOrderSchema = Joi.object({
id: id.required(),
})
const createOrderSchema = Joi.object({
customerId: customerId.required(),
});
module.exports = {
getOrderSchema,
createOrderSchema
}
¿Quieres ver más aportes, preguntas y respuestas de la comunidad?