Giter Site home page Giter Site logo

sequelize-i18n's Introduction

sequelize-i18n

Easily set up internalization using sequelize

Installation

Install with npm

npm install sequelize-i18n --save

Usage

###Model definition

Define your models as usal using sequelize, simply set i18n property to true for the internationnalised fields :

var Product = function (sequelize, DataTypes) {
    var Product = sequelize.define('product', {
        id : {
            type 			: DataTypes.BIGINT,
            primaryKey 		: true,
            autoIncrement 	: true
        },
        name : {
            type 			: DataTypes.STRING,
            i18n		 	: true
        },
        reference : {
            type 			: DataTypes.STRING
        }
    },
    
    { /* options */ });
    return Product;
};


module.exports = function(sequelize) {
    return sequelize.import('product', Product)
};

Initialisation

Init Sequelize-i18n module before importing models

var Sequelize = require('sequelize');
var SequelizeI18N = require('sequelize-i18n');

var languages = { 
	list : ["EN" , "FR" , "ES"] , 
	default : "FR" 
};

// Init Sequelize
sequelize = new Sequelize( "db_name" , "user" , "password" );

// Init i18n
i18n = new SequelizeI18N( sequelize, { languages: languages.list, default_language: languages.default } );
i18n.init();

// Import models in sequelize
var ProductModel = sequelize.import('product', Product)

Options

  • languages ( Array ) - List of allowed languages IDs
  • default_language ( Object ) - Default language ID
  • i18n_default_scope ( Boolean = true ) - Add i18n to the model default scope
  • add_i18n_scope ( Boolean = true ) - Add i18n scope to model
  • inject_i18n_scope ( Boolean = true ) - Inject i18n to model scopes
  • default_language_fallback ( Boolean = true ) - Fall back to default language if we can't find a value for the given language in get_i18n method

How it works


Sequelize-i18n will check for i18n property in your models properties. If i18n is set to true, it will create an new table in which internationalized values for the property will be store.

Example : The given the above exemple "Product",

name : {
    type 		: DataTypes.STRING,
    i18n		: true,
}

A Product_i18n Sequelize model will be create, with the following columns:

  • id : the row unique identifier ( INTEGER )
  • language_id : Identifies the language of the current translation ( INTEGER OR STRING )
  • parent_id : id of the targeted product ( Same the Product model primary key or unique key )
  • name : i18n value ( Same as Product.name.type )

The "name" property type will be set to VIRTUAL

Sequelize-i18n will set hooks into models on create, find, update and delete operations.

Creation

ProductModel.create({
     id: 1,
     name: 'test',
     reference: "xxx"
 })
 .then(function (result)  {
     // result.product_i18n == [ {name : "test" , lang : "FR" } ]
 })

Update

product_instance.update( { name : "new name" }  )
.then( function( result ) {
    // result.product_i18n = [ {name : "french name" , language_id : "FR" } ]
}
 
product_instance.update( { name : "english name" } , { language_id : "EN" }  )
.then( function( result ) {
    /*
    result.product_i18n == [ 
        {name : "french name" , language_id : "FR" } ,
        {name : "english name" , language_id : "EN" }
    ]
    */
}

Find

Product.find({ where : { id : 1 } })
.then( function( result ) {
    /*
    result.product_i18n == [ 
        {name : "french name" , language_id : "FR" } ,
        {name : "english name" , language_id : "EN" }
    ]
    */
});

Delete

Deleting a Product instance will also delete i18n values

get_i18n instance method

An Sequelize instance method is added to the Sequelize model in order to set virtual i18n property in the lanuage you want.

product_instance.get_i18n( "EN" );
// product_instance.name == "english name"

product_instance.get_i18n( "FR" );
// product_instance.name == "french name"

product_instance.get_i18n( "ES" );
// product_instance.name == "" if options.default_language_fallback is set to false
// product_instance.name == "french name" if options.default_language_fallback is set to true

sequelize-i18n's People

Contributors

adriencamy avatar camyadrien avatar

Stargazers

 avatar  avatar

Watchers

 avatar  avatar  avatar

sequelize-i18n's Issues

Language_id parameter has no effect on creation of object for FeathersJS app

Hi,

I've got an issue with the integration of sequelize-i18n on a FeathersJS app.

I've got a service called category. It's linked with a model called category. I can create new instance without any problem, but it always uses the default language I set.

Here's my repo: https://github.com/lionelrudaz/api.wellnow.ch

Here's what I send to create a new instance:

# Create a category
# 
curl -X "POST" "http://localhost:3030/categories" \
     -H "Accept-Language: fr" \
     -H "Content-Type: application/vnd.api+json" \
     -d "{\"rank\":\"12\",\"name\":\"Chiropractie\",\"slug\":\"physiotherapie\",\"language_id\":\"DE\"}"

I tried by sending language_id, lang and by defining Accept-Language. None of them work.

Do you have any clue?

Thanks in advance,

Lionel

Correct languages for dependencies

When i try to load dependencies which already defined as i18n ready, it will not fetch only determined language code, but all.

example:

  models.Category.findOne({
    where: {id : 1,language_id : 'en'},
    include:[{
        model : models.Post
      }
    ]
  }).then(function(result){
    console.log(result) ;
  });

It will print out all languages for a Post

i18n & findOrCreate

This is my route to create or update existing user's profile.

router.post('/p',function(req,res,next){
  req.body.UserId = req.decoded.id ;
	models.Profile
  .findOrCreate({where: {UserId: req.decoded.id}, defaults: req.body,language_id : req.body.language_id })
  .spread(function(profile, created) {
    if(!created) {
      profile.update(req.body, { language_id : req.body.language_id }).then(function(result){
        res.status(200).json({info : 'p100', text : 'Profile updated', l : req.body.language_id});
      });
    } else {
      res.status(200).json({info : 'p101', text : 'Profile created', l : req.body.language_id });
    }
  });
})

it is working correctly but show in the terminal these errors:

Unhandled rejection TypeError: fn is not a function
    at /root/API/node_modules/sequelize-i18n/lib/hooks/after-update.js:26:17
    at tryCatcher (/root/API/node_modules/bluebird/js/release/util.js:16:23)
    at Promise._settlePromiseFromHandler (/root/API/node_modules/bluebird/js/release/promise.js:512:31)
    at Promise._settlePromise (/root/API/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/root/API/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/root/API/node_modules/bluebird/js/release/promise.js:693:18)
    at Promise._fulfill (/root/API/node_modules/bluebird/js/release/promise.js:638:18)
    at Promise._resolveCallback (/root/API/node_modules/bluebird/js/release/promise.js:432:57)
    at Promise._settlePromiseFromHandler (/root/API/node_modules/bluebird/js/release/promise.js:524:17)
    at Promise._settlePromise (/root/API/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/root/API/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/root/API/node_modules/bluebird/js/release/promise.js:693:18)
    at Promise._fulfill (/root/API/node_modules/bluebird/js/release/promise.js:638:18)
    at Promise._resolveCallback (/root/API/node_modules/bluebird/js/release/promise.js:432:57)
    at Promise._settlePromiseFromHandler (/root/API/node_modules/bluebird/js/release/promise.js:524:17)
    at Promise._settlePromise (/root/API/node_modules/bluebird/js/release/promise.js:569:18)
    at Promise._settlePromise0 (/root/API/node_modules/bluebird/js/release/promise.js:614:10)
    at Promise._settlePromises (/root/API/node_modules/bluebird/js/release/promise.js:693:18)
    at Promise._fulfill (/root/API/node_modules/bluebird/js/release/promise.js:638:18)
    at Promise._resolveCallback (/root/API/node_modules/bluebird/js/release/promise.js:432:57)
    at Promise._settlePromiseFromHandler (/root/API/node_modules/bluebird/js/release/promise.js:524:17)
    at Promise._settlePromise (/root/API/node_modules/bluebird/js/release/promise.js:569:18)

I did review codes, but i couldn't find where i did mistake.

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.