Generating Joi validation a Sequelize model - node.js

I have developed an API using expressjs and Sequelize is the ORM I have used. I want to integrate express-validation to my API to validate the request body and params. The express-validation framework uses the Joi validation rules. But as I have already defined the validation rules in my Sequalize model, I' don't like to redefine validation rules using Joi for request body validations.
I'm just wondering if there's any method or library to generate Joi validation rules based on validations defined in Sequelize model. Else, what would be the best approach to handle this?

Have you checked out joi-sequelize ?

This question is too old however this answer maybe helpful for those newbies who are learning the language or maybe started working with sequelize
Sequelize provides validation by default. You can look into the docs
Sequelize Validation docs
However if you want to provide your own custom validators with custom "pretty" messages. You can always use the
#hapi/joi
package the "normal" way. joi-sequelize or sequelize-joi are not required just to provide custom error message.(period)
function validateData(datas) {
const schema = Joi.object({
user_name: Joi.string().min(3).required(),
user_address: Joi.string().required()
});
return schema.validate(datas);
}
and then validate the data using
const { error } = validateData(req.body);
which catches if any properties fails the validation.

Related

Pass fastify request schema to NestJS controller

I am trying to use fastify+NestJS. However, in order to use, in my opinion, the main strength of fastify, its speed, I need to get profit of fastify json schema. However, I do not understand how can I inject such a schema in a NestJS controller. Can you help me please?

Creating USERs table in Express

I'm pretty new to Express and NodeJS (less than a week) and I have a noobish question.
Background
I have made a REST API from a tutorial using Express and Passport for Authentication (which is just a basic auth with username and password and I get a token back in my requests).
I want to have something like Instagram or Facebook in which users have some information (name, birthdate etc.) and they can post texts.
Model/Account.js
import mongoose from 'mongoose';
const Schema = mongoose.Schema;
import passportLocalMongoose from 'passport-local-mongoose';
let Account = new Schema({
email: String,
password: String
});
Account.plugin(passportLocalMongoose);
module.exports = mongoose.model('Account', Account);
Problem
I don't know if I should add fields to the Model that I created for Authentication (which only has email and password) or I should create a separate Table, like USERS in my Database (I know it's a JSON file and not a database but don't know the technical name).
Please if any, give some hints here or keywords so that I can google myself.
Thanks a lot in advance :)
i think you should add the field is existing model that you create for Authentication because if you made another model you have to repeat the data in your case it is email and password which does not make any sense and it also cause problems and confusion to fetch or manage data in both tables so i prefer you to insert the field in same model that you create for Authentication
I would be inclined to reuse your accounts mongoose model for your user model.
Reason being is that you already have captured email and password which is what you would usually store in a user model.
You can add your additional fields to what you already have.
I think you should consider a general schema for account authentication model and use the schema in all authentication cases. I prefer add other fields to exist model.

Sanitization and Validations for Sails JS

I'm using sails js 0.11. Are the inputs using req.body or req.params.all() sanitized? If not, what should be done to sanitize them?
Secondly, for validations - where can the validations be done? Eg: req.params.all().id should be an integer type.
For sanitazing you can write hook or service
Validation rules should be described in your models

Middleware to validade all form entries express js, node js

Is there some middleware function to validate all entries in forms for node js and express js?
I want to check for special characteres and i don't want to validade each form field at each time.
Thanks!
The express-validator could be a good fit. It is built upon validator.js, a popular validation library.
The express-validator is also frequently updated.
1. Set up and init
expressValidator = require('express-validator');
app.use(expressValidator([options]));
see available options
2. Configure the validation
req.checkBody('postparam', 'Invalid postparam').notEmpty().isInt();
req.checkParams('urlparam', 'Invalid urlparam').isAlpha();
req.checkQuery('getparam', 'Invalid getparam').isInt();

mongoose and restify - localize strings before returning json

I would like to return localized Strings for multilanguage business objects in our RestFul API based on node.js, restify and mongoose. I have the requirement to store the translated resources on our translation resource server, but also need to support dynamic creation of those business objects.
I found a solution to easily plugin the i18n process in the POST/PUT calls using a single pre-'save' mongoose middleware on all Schema, when creating or updating my multi-languate business objects - this works because I am able to pass the request context to the obj.save(req, callback) call.
But, I am struggling to plug in the i18n on simple GETs. I thought of and tried different ways where I can plugin the i18n before returning the response, but don't really find a good way. Options I thought of:
translate in a mongoose middleware pre /post ('init'):
Problem: I don't have access to the request context, and therefore
don't know the locale to return, so I cannot translate there.
translate in the toObject() / toJSON {transform: }:
Same issue - i don't have the request context in these hooks.
translate in the handler/controller methods for each ressource.
Problem: Duplication, I have to do it everywhere, I would really prefer a solution I can define on the model/Schema layer
translate in a restify / express middleware towards the end:
Problem: I don't have access to the mongoose schema metainformation anymore, so I don't know which attriutes to translate.
Edit: just found this additional way:
- translate in a custom restify responseFormatter:
This seems to work nicely, in the reponseformatter I have access to everything I need. It kind of seems a little weird from an architechtural point of view, but if nobody has a better idea, I will add this as an answer.
Maybe (hopefully) I am missing something obvious...
thanks for any hints

Resources