Giter Club home page Giter Club logo

sequelize-fixtures's Introduction

Build Status

I'm no longer using Sequelize or this lib, and have very little motivation to maintain it. If someone wants to take over, let me know!

Sequelize fixtures

This is a simple lib to load data to database using sequelize.
It is intended for easily setting up test data.
Yaml and json formats are supported. Includes a grunt task.
Duplicate records are not inserted. API returns bluebird promises, but callbacks can also be used as the last argument.

Tested with latest Sequelize (4.0)

Install

npm install sequelize-fixtures

Test

npm test

Usage

    const sequelize_fixtures = require('sequelize-fixtures');

    //a map of [model name] : model
    //see offical example on how to load models
    //https://github.com/sequelize/express-example/blob/master/models/index.js
    const models = require('./models');

    //from file
    sequelize_fixtures.loadFile('fixtures/test_data.json', models).then(function(){
        doStuffAfterLoad();
    });

    //can use glob syntax to select multiple files
    sequelize_fixtures.loadFile('fixtures/*.json', models).then(function(){
        doStuffAfterLoad();
    });

    //array of files
    sequelize_fixtures.loadFiles(['fixtures/users.json', 'fixtures/data*.json'], models).then(function(){
        doStuffAfterLoad();
    });

    //specify file encoding (default utf8)
    sequelize_fixtures.loadFile('fixtures/*.json', models, { encoding: 'windows-1257'}).then(function(){
        doStuffAfterLoad();
    });

    //load fixtures inside a transaction
    sequelize.transaction(function(tx) {
        sequelize_fixtures.loadFile('fixtures/*.json', models, { transaction: tx}).then(doStuffAfterLoad);
    });

    //apply transform for each model being loaded
    sequelize_fixtures.loadFile('fixtures/*.json', models, {
        transformFixtureDataFn: function (data) {
          if(data.createdAt
           && data.createdAt < 0) {
            data.createdAt = new Date((new Date()).getTime() + parseFloat(data.createdAt) * 1000 * 60);
          }
          return data;
        }
    }).then(function() {
        doStuffAfterLoad();
    });

    //modify each model being loaded
    sequelize_fixtures.loadFile('fixtures/*.json', models, {
        modifyFixtureDataFn: function (data) {
          if(!data.createdAt) {
            data.createdAt = new Date();
          }
          return data;
        }
    }).then(function() {
        doStuffAfterLoad();
    });

    //from array
    var fixtures = [
        {
            model: 'Foo',
            data: {
                propA: 'bar',
                propB: 1
            }
        },
        {
            model: 'Foo',
            data: {
                propA: 'baz',
                propB: 3
            }
        }
    ];
    sequelize_fixtures.loadFixtures(fixtures, models).then(function(){
        doStuffAfterLoad();
    });

File formats

json

    [
        {
            "model": "Foo",
            "data": {
                "propA": "bar",
                "propB": 1
            }
        },
        {
            "model": "Foo",
            "data": {
                "propA": "baz",
                "propB": 3
            }
        }
    ]

yaml

    fixtures:
        - model: Foo
          data:
            propA: bar
            propB: 1
        - model: Foo
          data:
            propA: baz
            propB: 3

javascript

    module.exports = [
        {
            "model": "Foo",
            "data": {
                "propA": "bar",
                "propB": 1
            }
        },
        {
            "model": "Foo",
            "data": {
                "propA": "baz",
                "propB": 3
            }
        }
    ];

Associations

You can specify associations by providing related object id or a where clause to select associated object with. Make sure associated objects are described before associations!

One to many

Assuming

Car.belongsTo(Owner);
Owner.hasMany(Car);

Associated entity can be mapped by providing either an id:

[
    {
        "model": "Owner",
        "data": {
            "id": 11,
            "name": "John Doe",
            "city": "Vilnius"
        }
    },
    {
        "model": "Car",
        "data": {
            "id": 203,
            "make": "Ford",
            "owner": 11
        }
    }
]

Or a property-value map (like a 'where' object) to find the entity with:

[
    {
        "model": "Owner",
        "data": {
            "name": "John Doe",
            "city": "Vilnius"
        }
    },
    {
        "model": "Car",
        "data": {
            "make": "Ford",
            "owner": {
                "name": "John Doe"
            }
        }
    }
]

Many to many

Assuming

Project.belongsToMany(Person, {through: 'peopleprojects'});
Person.belongsToMany(Project, {through: 'peopleprojects'});

Associated entities can be mapped using the association 'as' name ('people' for Project and 'projects' for People) or 'through' table name, and providing an array of ids:

[
    {
        "model":"Person",
        "data":{
            "id":122,
            "name": "Jack",
            "role": "Developer"
        }
    },
    {
        "model":"Person",
        "data":{
            "id": 123,
            "name": "John",
            "role": "Analyst"
        }
    },
    {
        "model":"Project",
        "data": {
            "id": 20,
            "name": "The Great Project",
            "people": [122, 123]
        }
    }

]

Or an array of property-value mappings to find the entities with:

[
    {
        "model":"Person",
        "data":{
            "name": "Jack",
            "role": "Developer"
        }
    },
    {
        "model":"Person",
        "data":{
            "name": "John",
            "role": "Analyst"
        }
    },
    {
        "model":"Project",
        "data": {
            "name": "The Great Project",
            "people": [
                {                        
                    "name": "Jack"
                },
                {
                    "name": "John"
                }
            ]
        }
    }

]

If you have a custom through model for a m2m relationship, you can set additional attributes using _through:

ActorsMovies = sequelize.define("ActorsMovies", {
    character: {type: DataTypes.STRING}
});
Movie.belongsToMany(Actor, {through: ActorsMovies});
Actor.belongsToMany(Movie, {through: ActorsMovies});
[
    {
        "model": "Movie",
        "data": {
            "name": "Terminator"      
        }
    },
    {
        "model": "Actor",
        "data": {
            "name": "Arnie",
            "movies": [
                {
                    "name": "Terminator",
                    "_through": {
                        "character": "T-80"
                    }
                }
            ]
        }
    }
]

Build options, save options

For each model you can provide build options that are passed to Model.build() and save options that are passed to instance.save(), example:

{
    "model": "Article",
    "buildOptions": {
        "raw": true,
        "isNewRecord": true
    },
    "saveOptions": {
        "fields": ["title", "body"]
    },
    "data": {
        "title": "Any title",
        "slug": "My Invalid Slug"
    }
}

Detect duplicates based on select fields

In case you want to detect duplicates based on specific field or fields rather than all fields (for example, don't include entities with the same id, even if other fields don't match), you can speficy these fields with a 'keys' property.

{
    "model": "Person",
    "keys": ["email"],
    "data": {
        "name": "John",
        "email": "[email protected]"
    }
},
{
    "model": "Person",
    "keys": ["email"],
    "data": {
        "name": "Patrick",
        "email": "[email protected]"
    }
}

In this example only John will be loaded

grunt task

Gruntfile.js:

    grunt.initConfig({
        fixtures: {
            import_test_data: {
                src: ['fixtures/data1.json', 'fixtures/models*.json'],
                models: function () {  //returns mapping model name: model
                    return require('../models')
                },
                options: { //specify encoding, optiona. default utf-8
                    encoding: 'windows-1257'
                }
            }
        }

    });

    grunt.loadNpmTasks('sequelize-fixtures');

sequelize-fixtures's People

Contributors

dennisschaaf avatar dgmike avatar domasx2 avatar ekmartin avatar garrinmf avatar hawkaa avatar iamblue-mtk avatar jonathanargentiero avatar jordan-burnett avatar mabeebam avatar nedrocks avatar pcsanwald avatar publickeating avatar rfink avatar richayotte avatar rjz avatar samirsyed avatar samuelbolduc avatar sylwit avatar vsaienko avatar witem avatar

Watchers

 avatar  avatar

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.