Al intentar crear un customer en insomnia me arroja el siguiente error; ya repase el código varias veces y no encuentro mi error del por qué envía todo nulo:
{
"statusCode": 409,
"message": "SequelizeValidationError",
"errors": [
{
"message": "Customer.name cannot be null",
"type": "notNull Violation",
"path": "name",
"value": null,
"origin": "CORE",
"instance": {
"sendOffer": true,
"createdAt": "2023-07-03T00:48:01.470Z",
"id": null
},
"validatorKey": "is_null",
"validatorName": null,
"validatorArgs": []
},
{
"message": "Customer.lastName cannot be null",
"type": "notNull Violation",
"path": "lastName",
"value": null,
"origin": "CORE",
"instance": {
"sendOffer": true,
"createdAt": "2023-07-03T00:48:01.470Z",
"id": null
},
"validatorKey": "is_null",
"validatorName": null,
"validatorArgs": []
},
{
"message": "Customer.phone cannot be null",
"type": "notNull Violation",
"path": "phone",
"value": null,
"origin": "CORE",
"instance": {
"sendOffer": true,
"createdAt": "2023-07-03T00:48:01.470Z",
"id": null
},
"validatorKey": "is_null",
"validatorName": null,
"validatorArgs": []
}
]
}
Error que arroja en terminal:
ValidationError [SequelizeValidationError]: notNull Violation: Customer.name cannot be
null,
notNull Violation: Customer.lastName cannot be null,
notNull Violation: Customer.phone cannot be null
at InstanceValidator._validate (/home/practicas/e-wallet-
solo/node_modules/sequelize/lib/instance-validator.js:50:13)
at async InstanceValidator._validateAndRunHooks (/home/practicas/e-wallet-
solo/node_modules/sequelize/lib/instance-validator.js:60:7)
at async InstanceValidator.validate (/home/practicas/e-wallet-
solo/node_modules/sequelize/lib/instance-validator.js:54:12)
at async Customer.save (/home/practicas/e-wallet-
solo/node_modules/sequelize/lib/model.js:2426:7)
at async Customer.create (/home/practicas/e-wallet-
solo/node_modules/sequelize/lib/model.js:1362:12)
at async CustomerService.create (/home/practicas/e-wallet-
solo/services/customers.service.js:21:25)
at async /home/practicas/e-wallet-solo/routes/customers.router.js:42:28 {
errors: [
ValidationErrorItem {
message: 'Customer.name cannot be null',
type: 'notNull Violation',
path: 'name',
value: null,
origin: 'CORE',
instance: [Customer],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
},
ValidationErrorItem {
message: 'Customer.lastName cannot be null',
type: 'notNull Violation',
path: 'lastName',
value: null,
origin: 'CORE',
instance: [Customer],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
},
ValidationErrorItem {
message: 'Customer.phone cannot be null',
type: 'notNull Violation',
path: 'phone',
value: null,
origin: 'CORE',
instance: [Customer],
validatorKey: 'is_null',
validatorName: null,
validatorArgs: []
}
]
}
Código de customer.service
:
const boom = require('@hapi/boom')
const { models } = require('../libs/sequelize')
class CustomerService {
constructor() {}
async find() {
const customer = await models.Customer.findAll()
return customer
}
async findOne(id) {
const customer = await models.Customer.findByPk(id)
if(!customer) {
throw boom.notFound('customer not found')
}
return customer
}
async create(data) {
const newCustomer = await models.Customer.create(data)
return newCustomer
}
async update(id, changes) {
const model = await this.findOne(id)
const customer = await model.update(changes)
return customer
}
async delete(id) {
const model = await this.findOne(id)
await model.destroy()
return { rta: true }
}
}
module.exports = CustomerService
Código del index
de la carpeta routes
:
const express = require('express')
const customerRouter = require('./customers.router')
function routerApi(app) {
const router = express.Router()
app.use('/v1/', router)
router.use('/customers', customerRouter)
}
module.exports = routerApi
Código de customer.router
:
const express = require('express')
const CustomerService = require('../services/customers.service')
const validatorHandler = require('../middlewares/validator.handlres')
const { getCustomerSchema, createCustomerSchema, updateCustomerSchema } =
require('../schemas/customer.schema')
const router = express.Router()
const service = new CustomerService()
router.get('/',
async (req, res, next) => {
try {
const customers = await service.find()
res.json(customers)
} catch (error) {
next(error)
}
}
)
router.get(
'/:id',
validatorHandler(getCustomerSchema, 'params'),
async (req, res, next) => {
try {
const { id } = req.params
const customer = await service.findOne(id)
res.json(customer)
} catch (error) {
next(error)
}
}
)
router.post(
'/',
validatorHandler(createCustomerSchema, 'body'),
async (req, res, next) => {
try {
const body = req.body
res.status(201).json(await service.create(body))
} catch (error) {
next(error)
}
}
)
router.patch(
'/:id',
validatorHandler(getCustomerSchema, 'params'),
validatorHandler(updateCustomerSchema, 'body'),
async (req, res, next) => {
try {
const { id } = req.params
const body = req.body
const customer = await service.update(id, body)
res.json(customer)
} catch (error) {
next(error)
}
}
)
router.delete(
'/:id',
validatorHandler(getCustomerSchema, 'params'),
async (req, res) => {
const { id } = req.params
const customer = await service.delete(id)
res.json(customer)
}
)
module.exports = router
Código de customer.schema
:
const Joi = require('joi')
const id = Joi.number().integer()
const name = Joi.string()
const lastName = Joi.string()
const email = Joi.string().email()
const phone = Joi.string()
const totalSpent = Joi.number().integer()
const wallet = Joi.number().integer()
const sendOffer = Joi.boolean()
const getCustomerSchema = Joi.object({
id: id.required()
})
const createCustomerSchema = Joi.object({
name: name,
lastName: lastName,
email: email,
phone: phone,
sendOffer: sendOffer
})
const updateCustomerSchema = Joi.object({
name,
lastName,
email,
phone,
totalSpent,
wallet,
sendOffer,
})
module.exports = { getCustomerSchema, createCustomerSchema, updateCustomerSchema }
Les añado el customer.model
:
const { Model, DataTypes, Sequelize } = require('sequelize')
const CUSTOMER_TABLE = 'customers'
const CustomerSchema = {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: DataTypes.INTEGER
},
name: {
allowNull: false,
type: DataTypes.STRING
},
lastName: {
allowNull: false,
field: 'last_name',
type: DataTypes.STRING
},
email: {
allowNull: true,
type: DataTypes.STRING,
aunique: true
},
phone: {
allowNull: false,
type: DataTypes.STRING
},
totalSpent: {
allowNull: true,
field: 'total_spent',
type: DataTypes.INTEGER
},
wallet: {
allowNull: true,
type: DataTypes.INTEGER
},
sendOffer: {
allowNull: true,
field: 'send_offer',
type: DataTypes.BOOLEAN,
defaultValue: true
},
createdAt: {
allowNull: false,
type: DataTypes.DATE,
field: 'create_at',
defaultValue: Sequelize.NOW
}
}
class Customer extends Model {
static associate() {
//
}
static config(sequelize) {
return {
sequelize,
tableName: CUSTOMER_TABLE,
modelName: 'Customer',
timestamps: false
}
}
}
module.exports = { CUSTOMER_TABLE, CustomerSchema, Customer }
Código del index
de la carpeta model
:
const { Customer, CustomerSchema } = require('./customer.models')
function setupModels(sequelize) {
Customer.init(CustomerSchema, Customer.config(sequelize))
}
module.exports = setupModels
En el customer.models
eliminé los allowNull y si se creo pero todo estaba en null.
Código de la carpeta config
archivo config
:
require('dotenv').config()
const config = {
env: process.env.NODE_ENV || 'dev',
isProd: process.env.NODE_ENV === 'production',
port: process.env.PORT || 3000,
dbUrl: process.env.DATABASE_URL
}
module.exports = { config }
Código de config
de la carpeta models
:
const { config } = require('../config/config')
module.exports = {
development: {
url: config.dbUrl,
dialect: 'postgres',
},
production: {
url: config.dbUrl,
dialect: 'postgres',
ssl: {
rejectUnauthorized: false
}
}
}
Código de las migraciones:
'use strict'
const { CUSTOMER_TABLE } = require('../models/customer.models')
module.exports = {
async up (queryInterface, Sequelize) {
await queryInterface.createTable(CUSTOMER_TABLE, {
id: {
allowNull: false,
autoIncrement: true,
primaryKey: true,
type: Sequelize.DataTypes.INTEGER
},
name: {
allowNull: false,
type: Sequelize.DataTypes.STRING
},
lastName: {
allowNull: false,
field: 'last_name',
type: Sequelize.DataTypes.STRING
},
email: {
allowNull: true,
type: Sequelize.DataTypes.STRING,
unique: true
},
phone: {
allowNull: false,
type: Sequelize.DataTypes.STRING
},
totalSpent: {
allowNull: true,
field: 'total_spent',
type: Sequelize.DataTypes.INTEGER
},
wallet: {
allowNull: true,
type: Sequelize.DataTypes.INTEGER
},
sendOffer: {
allowNull: true,
field: 'send_offer',
type: Sequelize.DataTypes.BOOLEAN,
defaultValue: true
},
createdAt: {
allowNull: false,
type: Sequelize.DataTypes.DATE,
field: 'created_at',
defaultValue: Sequelize.fn("NOW")
}
})
},
async down (queryInterface) {
await queryInterface.dropTable(CUSTOMER_TABLE)
}
}
Código de sequelize
:
const { Sequelize } = require('sequelize')
const { config } = require('../config/config')
const setupModels = require('../db/models')
const options = {
dialect: 'postgres',
logging: config.isProd ? false : true
}
if(config.isProd) {
options.dialectOptions = {
ssl: {
rejectUnauthorized: false
}
}
}
const sequelize = new Sequelize(config.dbUrl, options)
setupModels(sequelize)
module.exports = sequelize
Código de los middlewares
:
errorHandler
:
const { ValidationError } = require("sequelize")
const boom = require('@hapi/boom')
function logErrors (err, req, res, next) {
console.error(err);
next(err);
}
function errorHandler(err, req, res, next) {
res.status(500).json({
message: err.message,
stack: err.stack,
});
}
function boomErrorHandler(err, req, res, next) {
if (err.isBoom) {
const { output } = err;
res.status(output.statusCode).json(output.payload);
} else {
next(err);
}
}
function ormErrorHandler(err, req, res, next) {
if(err instanceof ValidationError) {
res.status(409).json({
statusCode: 409,
message: err.name,
errors: err.errors
})
} else {
next(err)
}
}
module.exports = { logErrors, errorHandler, boomErrorHandler, ormErrorHandler }
validator.handler
:
const boom = require('@hapi/boom')
function validatorHandler(schema, property) {
return (req, res, next) => {
const data = req[property]
const { error } = schema.validate(data, { abortEarly: false })
if (error) {
next(boom.badRequest(error))
} else {
next()
}
}
}
module.exports = validatorHandler
Código del index
del proyecto:
const express = require('express')
const cors = require('cors')
const routerApi = require('./routes')
const { logErrors, errorHandler, boomErrorHandler, ormErrorHandler } = require('./middlewares/error.handler')
const app = express()
const port = process.env.PORT || 3000
app.use(express.json())
const whiteList = [ 'http://localhost:8080', 'http://localhost:3000' ]
const options = {
origin: (origin, callback) => {
if(whiteList.includes(origin)) {
callback(null, true)
} else {
callback(new Error('No Permitido'))
}
}
}
app.use(cors(options))
routerApi(app)
app.use(logErrors);
app.use(ormErrorHandler);
app.use(boomErrorHandler);
app.use(errorHandler);
app.listen(port)
Esta es la ruta que utilizo en insomnia para crear un customer.
http://localhost:3000/v1/customers
Así es como estoy intentando crear un customer desde insomnia
{
"name": "ed",
"lastName": "cam",
"email": "[email protected]",
"phone": "667545454",
"totalSpent": 100,
"wallet": 10,
"sendOffer": true
}
Estas son todas las dependecias que tengo instaladas y sus versiones:
"devDependencies": {
"eslint": "^8.43.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-prettier": "^4.2.1",
"nodemon": "^2.0.22",
"prettier": "^2.8.8",
"sequelize-cli": "^6.6.1"
},
"dependencies": {
"@hapi/boom": "^10.0.1",
"cors": "^2.8.5",
"dotenv": "^16.3.1",
"express": "^4.18.2",
"joi": "^17.9.2",
"pg": "^8.11.1",
"pg-hstore": "^2.3.4",
"sequelize": "^6.32.1"
}