Coder Social home page Coder Social logo

joi-sequelize's People

Contributors

dancrumb avatar joeybaker avatar markgaucher avatar mibrito avatar wkopen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar

joi-sequelize's Issues

API could be simplified and better redesigned

It seems like an injection in the document to let user to access validations via sequelize instance:

.forEach(function (file) {
  var model = sequelize['import'](path.join(__dirname, file));
  db[model.name] = model;
  db.JS[model.name] = new JoiSequelize(require(path.join(__dirname, file)));
});

I think it could be better and simpler if redesign like this:

.forEach(function (file) {
  joiImport(file); // only one line to import and inject the model object
});

In joiImport(file) 2 things will be done:

function joiImport(file, sequelize) {
  // 1. normally import the model file.
  var model = sequelize['import'](path.join(__dirname, file));

  // 2. add the new joi instance to model object, and via it.
  model.joi = new JoiSequelize(model);
}

This will avoid additional JS instance to be present, which very hard to understand. But just add a method on each model, which looks more OO (Object Oriented) like.

And then you could use sequelize.models.User.joi() rather than db.JS.User.joi().

Problem with Usage guide?


const Hapi = require('hapi');
const db = require('./model');
const JS = db.JS;

const server = new Hapi.Server();
server.connection({ port: 3000 });

const JS = new JoiSequelize(model)

you override JS which you cant do because they are consts, then you dont use db.JS.

Am I missing something here?

model define throw "TypeError: DataTypes.ARRAY is not a function"

model define:

module.exports = (sequelize, DataTypes) => {
    var Student = sequelize.define('Student', { 
        residence: DataTypes.ARRAY(DataTypes.STRING),
    },
        {
            classMethods: {
                associate: function (models) {
                    // associations can be defined here
                }
            },
            underscored: true
        });
 
    return Student;
};

throw error:

/Users/xjnotxj/Program/NodeJsProject/sequelize_demo/backend/models/student.js:25
        residence: DataTypes.ARRAY(DataTypes.STRING),
                             ^

TypeError: DataTypes.ARRAY is not a function
    at module.exports (/Users/xjnotxj/Program/NodeJsProject/sequelize_demo/backend/models/student.js:25:30)
    at new JoiSequelize (/Users/xjnotxj/Program/NodeJsProject/sequelize_demo/backend/node_modules/joi-sequelize/index.js:14:3)
    at fs.readdirSync.filter.forEach.file (/Users/xjnotxj/Program/NodeJsProject/sequelize_demo/backend/models/index.js:29:25)
    at Array.forEach (<anonymous>)
    at Object.<anonymous> (/Users/xjnotxj/Program/NodeJsProject/sequelize_demo/backend/models/index.js:25:4)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/xjnotxj/Program/NodeJsProject/sequelize_demo/backend/middleware/valication.js:3:16)
    at Module._compile (module.js:635:30)
    at Object.Module._extensions..js (module.js:646:10)
    at Module.load (module.js:554:32)
    at tryModuleLoad (module.js:497:12)
    at Function.Module._load (module.js:489:3)
    at Module.require (module.js:579:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> (/Users/xjnotxj/Program/NodeJsProject/sequelize_demo/backend/app.js:23:9)
    at Module._compile (module.js:635:30)

Does this work with only HapiJs framework?

The Readme doc specifies the usage

server.route({
  method:  'POST',
  path:    '/hello',
  handler: (request, reply) => reply(request.payload),
  config:  {
    validate: {
      payload: JS.User.joi()
    }
  }
});

which looks like a routing config for HapiJs.
What does the statement JS.User.joi() return?
Can it be used in an expressJS server with a normal Joi.validate() api?

JS.User.joi() returns empty object

Here is code the

'use strict';

var fs        = require('fs'),
    path      = require('path'),
    Sequelize = require('sequelize'),
    JoiSequelize = require('joi-sequelize'),
    basename  = path.basename(module.filename),
    env       = process.env.NODE_ENV || 'development',
    // log       = (!process.env.LOG || process.env.LOG === 'false') ? false : true,
    config    = require('../config/config.json')[env],
    db,
    sequelize;

function init() {
  db = {};
  // config.logging = (env === 'development' && log) ? console.log : false;

  // if (config.use_env_variable) {
    // sequelize = new Sequelize(process.env[config.use_env_variable]);
  // } else {
  sequelize = new Sequelize(config.database, config.username, config.password, config);
  // }

  db.sequelize = sequelize;
  db.Sequelize = Sequelize;
  db.JS = {};
  fs
    .readdirSync(__dirname)
    .filter(file => (
        (file.indexOf('.') !== 0) &&
        (file !== basename) &&
        (file.slice(-3) === '.js')
      )
    )
    .forEach(function (file) {
      var model = sequelize['import'](path.join(__dirname, file));
      db[model.modelName] = model;
      db.JS[model.modelName] = new JoiSequelize(require(path.join(__dirname, file)));
    });

  Object.keys(db).forEach(function (modelName) {
        if (db[modelName].associate) {
          db[modelName].associate(db);
        }
      });

  Object.keys(db).forEach(function (modelName) {
    if (db[modelName].addScopes) {
      db[modelName].addScopes(db);
    }

    if (db[modelName].addHooks) {
      db[modelName].addHooks(db);
    }
  });
  console.log(db.JS.User.joi());
  return db;
}

module.exports = db || init();
```
`
Here is the model
`const AuditBase = require('./common/AuditBase');
const { DataTypes } = require('sequelize');

module.exports = () => {
  return {
    modelName: 'User',
    attributes: Object.assign({
      id: { type: DataTypes.STRING(36), primaryKey: true },
      name: { type: DataTypes.TEXT },
      tagline: { type: DataTypes.STRING(500) },
      bio: { type: DataTypes.STRING(2000) },
      link: { type: DataTypes.STRING },
      firstName: { type: DataTypes.STRING },
      lastName: { type: DataTypes.STRING },
      displayName: { type: DataTypes.STRING },
      gender: { type: DataTypes.ENUM('Female', 'Male', 'Transgender', 'Other') },
      birthday: { type: DataTypes.DATE },
      hometown: { type: DataTypes.STRING },
      auth0Id: { type: DataTypes.STRING },
      vetted: { type: DataTypes.BOOLEAN, defaultValue: false },
      slug: {
          type: DataTypes.STRING,
          allowNull: false,
          unique: true
      },
      avatarUrl: { type: DataTypes.STRING },
      coverImage: { type: DataTypes.STRING },
    }, AuditBase()),
    options: {
      tableName: 'users',
      freezeTableName: true,
      underscored: false,
      defaultScope: {
        attributes: ['id', 'name', 'tagline', 'bio', 'link', 'firstName',
              'lastName', 'displayName', 'gender', 'birthday', 'hometown',
              'slug', 'avatarUrl', 'coverImage'],
      },
      timestamps: true,
      updatedAt: 'updatedOn',
      createdAt: 'createdOn',
    },
  };
}
`

Sequilize validate rules

Hi, nice library.

Any plan/thoughts about supporting the validate rules of sequelize?

validate: {
        isEmail: true,
        len: [1, 255]
}

Createdat, Updatedat, Deletedat, Foreign keys not recognized

Is there any way for joi seqeulize to accept options passed in to sequelize (paranoid, underscore) to add these keys to the joi models? Especially the foreign keys, which i feel may be hard to do considering joi seqeulize doesnt actually use the sequelize instance.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.