### Install sequelize-fixtures Source: https://github.com/domasx2/sequelize-fixtures/blob/master/README.md Install the sequelize-fixtures package via npm. ```bash npm install sequelize-fixtures ``` -------------------------------- ### readFiles usage example Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/reader.md Example usage of readFiles. Creates a Reader instance and calls readFiles with an array of file paths and glob patterns. Logs the concatenated fixtures array on success. ```javascript const reader = new Reader({}); reader.readFiles(['fixtures/users.json', 'fixtures/data*.json']) .then(fixtures => console.log(fixtures)); ``` -------------------------------- ### readFileGlob usage example Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/reader.md Example usage of readFileGlob. Creates a Reader instance and calls readFileGlob with a glob pattern. Logs the number of fixtures on success or the error message on failure. ```javascript const reader = new Reader({}); reader.readFileGlob('fixtures/*.json') .then(fixtures => console.log(fixtures.length)) .catch(err => console.error(err.message)); // "No files matching '...' found." ``` -------------------------------- ### Load fixtures from glob with loadFile Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/index.md Example of loading fixtures from a glob pattern. The promise resolves after loading; errors include 'No files matching ...' and 'unknown file type: '. ```javascript sequelize_fixtures .loadFile('fixtures/*.json', models) .then(() => doStuffAfterLoad()); ``` -------------------------------- ### loadFiles usage example with globs Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/index.md Example usage of loadFiles with an array of file paths and glob patterns. The promise resolves to an object with a count property, which is logged to the console. ```javascript sequelize_fixtures .loadFiles(['fixtures/users.json', 'fixtures/data*.json'], models) .then(({ count }) => console.log(`${count} fixtures loaded`)); ``` -------------------------------- ### Winston-compatible object logger example Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/logger.md Example of using the logger factory with an object, providing custom implementations for debug, info, warn, and error. This is winston-compatible. ```javascript const log = logger({ debug: console.log, info: console.log, warn: console.log, error: (message) => console.error('OH NO! ERROR: ' + message), }); ``` -------------------------------- ### YAML fixture file format Source: https://github.com/domasx2/sequelize-fixtures/blob/master/README.md Example YAML fixture file format using a fixtures key with model and data entries. ```yaml fixtures: - model: Foo data: propA: bar propB: 1 - model: Foo data: propA: baz propB: 3 ``` -------------------------------- ### JavaScript fixture file format Source: https://github.com/domasx2/sequelize-fixtures/blob/master/README.md Example JavaScript fixture file format: module.exports an array of fixture objects. ```javascript module.exports = [ { "model": "Foo", "data": { "propA": "bar", "propB": 1 } }, { "model": "Foo", "data": { "propA": "baz", "propB": 3 } } ]; ``` -------------------------------- ### YAML fixture file with fixtures root key Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/types.md Example YAML fixture file. The root key 'fixtures:' is unwrapped by the Reader, and the file must evaluate to an array of fixture documents. ```yaml fixtures: - model: Foo data: propA: bar propB: 1 ``` -------------------------------- ### Consumer code example - using loadFixture Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/promise.md Shows how a consumer uses the returned promise from loadFixture without importing the Promise module. The promise is chained with .then and .catch to handle success and error. ```javascript const sf = require('sequelize-fixtures'); const promise = sf.loadFixture({ model: 'Foo', data: { propA: 'bar' } }, models); promise.then(() => console.log('done')).catch(err => console.error(err.message)); ``` -------------------------------- ### Function logger example Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/logger.md Example of using the logger factory with a function. The function is used for info, warn, and error, while debug remains a no-op. This also covers the 'log' option. ```javascript const logger = require('sequelize-fixtures/lib/logger'); const log = logger(function (message) { console.log('Fixtures:', message); }); log.debug('debug is a no-op for function loggers'); log.info('processing ...'); log.error('boom'); ``` -------------------------------- ### JSON fixture file format Source: https://github.com/domasx2/sequelize-fixtures/blob/master/README.md Example JSON fixture file format: an array of objects with model and data properties. ```json [ { "model": "Foo", "data": { "propA": "bar", "propB": 1 } }, { "model": "Foo", "data": { "propA": "baz", "propB": 3 } } ] ``` -------------------------------- ### Example - spread-style destructuring of prepFixtureData Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/promise.md Demonstrates using the spread method on the promise returned by prepFixtureData to destructure the result into data and many2many arguments. ```javascript const Loader = require('sequelize-fixtures/lib/loader'); new Loader({}).prepFixtureData({ propA: 'bar' }, models.Foo) .spread((data, many2many) => console.log(Object.keys(data), many2many)); ``` -------------------------------- ### loadFixtures usage example Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/loader.md Example of using loadFixtures with a Loader instance. The fixtures array contains two fixture documents, and the result includes count and models. Requires a models map of Sequelize models. ```javascript const Loader = require('sequelize-fixtures/lib/loader'); const loader = new Loader({ /* options */ }); loader.loadFixtures([ { model: 'Owner', data: { id: 11, name: 'John Doe' } }, { model: 'Car', data: { id: 203, make: 'Ford', owner: 11 } }, ], models).then(result => { console.log(result.count); // rows inserted console.log(result.models.Owner); // [instance] }); ``` -------------------------------- ### Load in-memory fixture array with loadFixtures Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/index.md Example of loading an in-memory fixture array. The fixtures are processed sequentially and the promise resolves to an object with a count of saved rows (duplicates skipped). ```javascript const fixtures = [ { model: 'Foo', data: { propA: 'bar', propB: 1 } }, { model: 'Foo', data: { propA: 'baz', propB: 3 } }, ]; sequelize_fixtures .loadFixtures(fixtures, models) .then(({ count }) => console.log(`${count} fixtures loaded`)); ``` -------------------------------- ### Configure fixtures task in Gruntfile Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/grunt-task.md Example configuration for the 'fixtures' multi-task from the README. It sets src patterns, an async models function, and an options object with a custom encoding. The grunt.loadNpmTasks('sequelize-fixtures') call loads the plugin. ```javascript grunt.initConfig({ fixtures: { import_test_data: { src: ['fixtures/data1.json', 'fixtures/models*.json'], // supports async loading models models: async function () { return await loadModels(); }, options: { //specify encoding, optional default utf-8 encoding: 'windows-1257' } } } }); grunt.loadNpmTasks('sequelize-fixtures'); ``` -------------------------------- ### Basic loadFixture call Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/index.md Basic usage example for loadFixture. It requires the module, loads a single fixture document with model 'Foo' and data, and logs a message on success. The models argument is a map of model name to Sequelize model. ```javascript const sequelize_fixtures = require('sequelize-fixtures'); const models = require('./models'); // map of model name -> Sequelize model sequelize_fixtures .loadFixture({ model: 'Foo', data: { propA: 'bar', propB: 1 } }, models) .then(() => console.log('fixture loaded')); ``` -------------------------------- ### Direct use of prepFixtureData to inspect resolved data Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/loader.md Example showing how to call prepFixtureData directly on a Loader instance to resolve a BelongsTo association and log the foreign key value, with many-to-many collections available in the second element of the resolved array. ```javascript const Loader = require('sequelize-fixtures/lib/loader'); const loader = new Loader({}); loader.prepFixtureData({ owner: { name: 'John Doe' } }, models.Car).then(([data, many2many]) => { console.log(data.ownerId); // foreign key value resolved from the "where" lookup // many2many would hold HasMany/BelongsToMany collections }); ``` -------------------------------- ### models map example with sequelize.import Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/types.md Shows the expected shape of the models map: an object mapping model names to Sequelize model instances. The loader validates each entry lazily, raising 'Model not found: ...' for missing names, a factory-function error for plain functions, and '... is not a sequelize model.' when findOne is missing. ```javascript { Foo: sequelize.import(__dirname + '/Foo') } ``` -------------------------------- ### Basic load with options and error handling Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/loader.md Shows how to create a Loader instance with a transaction and load a fixture. The loadFixture call returns a promise that logs 'ok' on success or logs the error message on failure. ```javascript const Loader = require('sequelize-fixtures/lib/loader'); const loader = new Loader({ transaction: currentTx }); loader.loadFixture({ model: 'Foo', data: { propA: 'bar', propB: 1 } }, models) .then(() => console.log('ok')) .catch(err => console.error('failed:', err.message)); ``` -------------------------------- ### Run tests Source: https://github.com/domasx2/sequelize-fixtures/blob/master/README.md Run the test suite for the project. ```bash npm test ``` -------------------------------- ### Provide build and save options Source: https://github.com/domasx2/sequelize-fixtures/blob/master/README.md Fixture object showing how to provide buildOptions passed to Model.build() and saveOptions passed to instance.save() for each model. ```json { "model": "Article", "buildOptions": { "raw": true, "isNewRecord": true }, "saveOptions": { "fields": ["title", "body"] }, "data": { "title": "Any title", "slug": "My Invalid Slug" } } ``` -------------------------------- ### Load fixtures with options (encoding, logger, transformFixtureDataFn) Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/configuration.md Shows how to pass options to loadFile: encoding, a structured logger, and a transformFixtureDataFn that adjusts createdAt values. The logger's error function logs a custom message. The promise resolves with 'done' after loading. ```javascript const sequelize_fixtures = require('sequelize-fixtures'); sequelize_fixtures.loadFile('fixtures/*.json', models, { encoding: 'windows-1257', // option 1: file encoding logger: { // option 2: structured logger debug: console.log, info: console.log, warn: console.log, error: (m) => console.error('OH NO! ERROR: ' + m), }, transformFixtureDataFn: function (data) { // option 3: value transform if (data.createdAt < 0) { data.createdAt = new Date(Date.now() + parseFloat(data.createdAt) * 1000 * 60); } return data; }, }).then(() => console.log('done')); ``` -------------------------------- ### Detect duplicates with keys property Source: https://github.com/domasx2/sequelize-fixtures/blob/master/README.md Fixture objects using the 'keys' property to detect duplicates based on specific fields. In this example, only John will be loaded because both have the same email. ```json { "model": "Person", "keys": ["email"], "data": { "name": "John", "email": "example@example.com" } }, { "model": "Person", "keys": ["email"], "data": { "name": "Patrick", "email": "example@example.com" } } ``` -------------------------------- ### Load fixtures with sequelize-fixtures Source: https://github.com/domasx2/sequelize-fixtures/blob/master/README.md Shows the main API usage: loadFile, loadFiles, loadFixtures, and options like encoding, log, logger, transaction, transformFixtureDataFn, and modifyFixtureDataFn. Requires a models map and returns a bluebird promise (callbacks also supported). ```javascript 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(); }); //specify logging function (default console.log) function myLogging(defaultLog) { console.log('Fixtures: processing ...') } sequelize_fixtures.loadFile('fixtures/*.json', models, { log: myLogging}).then(function(){ doStuffAfterLoad(); }); //specify separate stdout and stderr streams //(e.g. a winston-compatible logger) function errorReporter(message) { console.error('OH NO! ERROR: ' + message); } sequelize_fixtures.loadFile('fixtures/*.json', models, { logger: { debug: console.log, info: console.log, warn: console.log, error: errorReporter } }).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(); }); ``` -------------------------------- ### Define User model with setter that raises error Source: https://github.com/domasx2/sequelize-fixtures/blob/master/README.md Example of a model definition with a setter that uses `this.previous('email')`, which will raise an error when the library attempts to run values through setters by default. ```javascript const User = sequelize.define('User', email: { type: DataTypes.STRING, unique: true, validate: { isEmail: true, }, set: function set(val) { if (this.previous('email')) { // <--- this line will raise an error // check some thing } this.setDataValue('email', val); } } }); ``` -------------------------------- ### initopts() default options helper Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/index.md Applies the default option value. If no options object is provided, an empty object is used. The encoding option defaults to 'utf8' when not specified. ```js function initopts(options){ options = options || {}; options.encoding = options.encoding || 'utf8'; return options; } ``` -------------------------------- ### loadFixture error handling Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/index.md Error handling example for loadFixture. It attaches a catch handler to log the error message if the fixture load fails. The promise rejects with any of the errors listed in errors.md, plus 'Insufficient arguments' when called without models. ```javascript sequelize_fixtures .loadFixture({ model: 'Foo', data: { propA: 'bar' } }, models) .catch(err => { console.error('Fixture load failed:', err.message); }); ``` -------------------------------- ### Read a JS fixture module Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/reader.md Shows a JS fixture module that exports an array of fixtures, and how to read it with readFile. The module must export an array (or anything loadFixtures can iterate). ```js // fixtures/data.js module.exports = [ { model: 'Foo', data: { propA: 'bar', propB: 1 } }, ]; ``` ```js const reader = new Reader({}); reader.readFile('./fixtures/data.js') .then(fixtures => console.log(fixtures)) .catch(err => console.error(err.message)); // e.g. if the module throws ``` -------------------------------- ### loadFixtures(fixtures, models) Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/loader.md Loads an array of fixture documents sequentially using Promise.each. Resolves with a result object containing the count of saved fixtures and the map of loaded models. Rejects if any fixture fails, aborting the entire batch. ```APIDOC ## loadFixtures(fixtures, models) ### Description Loads an array of fixture documents sequentially. Processes each fixture via `loadFixture` in order, stopping on the first error. ### Method `loadFixtures(fixtures, models)` ### Parameters - **fixtures** (array) - Required - Array of fixture documents, processed sequentially via `Promise.each`. - **models** (object) - Required - Map of `{ [modelName]: SequelizeModel }`. ### Return `Promise<{ count: number, models: object }>` - Resolves with an object containing `count` (the number of saved fixtures) and `models` (the `fixtureModels` map). Rejects with the error of the first failing fixture; no per-fixture error isolation. ### Example ```js const Loader = require('sequelize-fixtures/lib/loader'); const loader = new Loader({ /* options */ }); loader.loadFixtures([ { model: 'Owner', data: { id: 11, name: 'John Doe' } }, { model: 'Car', data: { id: 203, make: 'Ford', owner: 11 } }, ], models).then(result => { console.log(result.count); // rows inserted console.log(result.models.Owner); // [instance] }); ``` ``` -------------------------------- ### `readFile(filename)` Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/reader.md Documentation for the `readFile` method of the `Reader` class in the sequelize-fixtures library. ```APIDOC ## `readFile(filename)` ### Description Reads a single fixture file and resolves to an array of fixture documents. Supports JavaScript modules, JSON, and YAML files, with extension-based behavior. ### Method `readFile` (instance method) ### Endpoint `Reader.prototype.readFile(filename)` ### Parameters - **filename** (string) - Required - Path to a single fixture file, e.g. `'fixtures/test_data.json'`. Relative paths are resolved from `process.cwd()`. ### Return Promise resolving to an array of fixture documents. ### Behavior by Extension - `.js` - Returns `require(path.resolve(process.cwd(), filename))`. The file must `module.exports` an array of fixtures (or anything `loadFixtures` can iterate). - `.json` / `.yml` / `.yaml` - Reads the file with `fs.readFileAsync(filename, this.options.encoding)`, runs it through the matching parser, and if the parsed document has a `fixtures` property, unwraps it. The YAML/JSON document must otherwise be an array. - Any other extension - Rejects with `Error('unknown file type: ', ext)`. Note the `Error` constructor receives two arguments; the second is ignored, so the resulting message is exactly `'unknown file type: '`. ### Logging Logs `logger.debug('Fixtures: reading file ' + filename + '...')` first. ### Example - Read a Single File ```js const Reader = require('sequelize-fixtures/lib/reader'); const reader = new Reader({ encoding: 'utf8' }); reader.readFile('./fixtures/data.json').then(fixtures => { console.log(fixtures.length); // parsed fixture array }); ``` ### Example - A JS Fixture Module ```js // fixtures/data.js module.exports = [ { model: 'Foo', data: { propA: 'bar', propB: 1 } }, ]; ``` ```js const reader = new Reader({}); reader.readFile('./fixtures/data.js') .then(fixtures => console.log(fixtures)) .catch(err => console.error(err.message)); // e.g. if the module throws ``` ``` -------------------------------- ### Full source of lib/Promise.js Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/promise.md The complete source code of the Promise module. It attempts to require Sequelize's Promise, falling back to bluebird if Sequelize's Promise is falsy or if Sequelize cannot be loaded. ```javascript var Promise; try { Promise = require('sequelize').Promise; if (!Promise) throw new Error(); } catch (err) { Promise = require('bluebird'); } module.exports = Promise; ``` -------------------------------- ### Reader constructor (lib/reader.js:9-13) Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/reader.md Constructs a Reader instance. Applies the encoding default ('utf8') and sets up the logger from options.log or options.logger. Unlike Loader, the Reader constructor mutates and applies the encoding default itself. ```javascript var Reader = module.exports = function (options) { options.encoding = options.encoding || 'utf8'; this.options = options; this.logger = logger(options.log || options.logger); }; ``` -------------------------------- ### loadFixtures(fixtures, models [, options] [, cb]) Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/index.md Loads an array of fixture documents sequentially. Returns a promise resolving to an object with the count of rows saved and the models created or found. ```APIDOC ## loadFixtures(fixtures, models [, options] [, cb]) ### Description Loads an array of fixture documents sequentially. Returns a promise resolving to an object with the count of rows saved and the models created or found. ### Method Function call ### Signature `loadFixtures(fixtures, models [, options] [, cb])` ### Parameters - **fixtures** (array) - Required - Array of fixture documents; processed sequentially in order - **models** (object) - Required - Map of `{ [modelName]: SequelizeModel }` - **options** (object) - Optional - Default: `{}` - See configuration.md - **cb** (function) - Optional - Deprecated callback ### Return Promise resolving to the result object `{ count: number, models: object }` — `count` is the number of rows actually saved (duplicates are skipped), `models` maps each `Model.name` to the array of Sequelize instances found-or-created for it. ### Example ```js const fixtures = [ { model: 'Foo', data: { propA: 'bar', propB: 1 } }, { model: 'Foo', data: { propA: 'baz', propB: 3 } }, ]; sequelize_fixtures .loadFixtures(fixtures, models) .then(({ count }) => console.log(`${count} fixtures loaded`)); ``` ``` -------------------------------- ### loadFile(filename, models [, options] [, cb]) Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/index.md Loads fixtures from a file path or glob pattern. Returns a promise resolving to the same result object as loadFixtures. ```APIDOC ## loadFile(filename, models [, options] [, cb]) ### Description Loads fixtures from a file path or glob pattern. Returns a promise resolving to the same result object as loadFixtures. ### Method Function call ### Signature `loadFile(filename, models [, options] [, cb])` ### Parameters - **filename** (string) - Required - File path or **glob pattern** (delegated to `RegExp`-free `glob`) - **models** (object) - Required - Map of `{ [modelName]: SequelizeModel }` - **options** (object) - Optional - Default: `{}` - See configuration.md - **cb** (function) - Optional - Deprecated callback ### Return Promise resolving to `{ count, models }` (the `loadFixtures` result). Rejection conditions from the reader: `"No files matching ..."` when the pattern matches nothing, `'unknown file type: '` for unsupported extensions. ### Example ```js sequelize_fixtures .loadFile('fixtures/*.json', models) .then(() => doStuffAfterLoad()); ``` ``` -------------------------------- ### readFile method signature Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/reader.md Shows the signature of the readFile method, which is wrapped with bluebird's Promise.method so that synchronous errors become promise rejections. ```js Reader.prototype.readFile = Promise.method(function(filename) { ``` -------------------------------- ### Read a single JSON fixture file Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/reader.md Reads a single JSON fixture file with the Reader instance. The promise resolves to an array of fixture documents. ```js const Reader = require('sequelize-fixtures/lib/reader'); const reader = new Reader({ encoding: 'utf8' }); reader.readFile('./fixtures/data.json').then(fixtures => { console.log(fixtures.length); // parsed fixture array }); ``` -------------------------------- ### loadFixtures implementation (lib/loader.js:15-21) Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/loader.md The core implementation of loadFixtures, which uses Promise.each to process fixtures sequentially. If any fixture fails, the entire batch rejects. Returns a promise resolving to { count: this.saved, models: this.fixtureModels }. ```javascript Loader.prototype.loadFixtures = function(fixtures, models) { return Promise.each(fixtures, function(fixture) { return this.loadFixture(fixture, models); }.bind(this)).then(function() { return Promise.resolve({count:this.saved, models:this.fixtureModels}); }.bind(this)); }; ``` -------------------------------- ### Module graph for sequelize-fixtures index.js Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/index.md Shows the module dependency graph for the package entry point. The Loader class is used by all four exported functions, while the Reader class is used only by loadFile and loadFiles. ```text index.js ├── lib/loader.js (Loader — used by all four functions) └── lib/reader.js (Reader — used by loadFile and loadFiles only) ``` -------------------------------- ### Configure grunt task for fixtures Source: https://github.com/domasx2/sequelize-fixtures/blob/master/README.md Grunt task configuration for importing fixtures, supporting async model loading and specifying encoding (default utf-8). ```javascript grunt.initConfig({ fixtures: { import_test_data: { src: ['fixtures/data1.json', 'fixtures/models*.json'], // supports async loading models models: async function () { return await loadModels(); }, options: { //specify encoding, optional default utf-8 encoding: 'windows-1257' } } } }); grunt.loadNpmTasks('sequelize-fixtures'); ``` -------------------------------- ### readFiles(filenames) Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/reader.md Reads multiple files and/or glob patterns, returning a promise resolving to the concatenation of all fixtures in the given order. Errors from any entry reject the whole promise. ```APIDOC ## readFiles(filenames) ### Description Reads multiple files and/or glob patterns, returning a promise resolving to the concatenation of all fixtures in the given order. Errors from any entry (e.g. missing glob match) reject the whole promise. ### Method readFiles ### Parameters - `filenames` (array) - Required - Array of file paths and/or glob patterns; every entry goes through `readFileGlob`. ### Return Promise resolving to the concatenation of all files' fixtures, in the given order. ### Example ```js const reader = new Reader({}); reader.readFiles(['fixtures/users.json', 'fixtures/data*.json']) .then(fixtures => console.log(fixtures)); ``` ``` -------------------------------- ### loadFixture(fixture, models [, options] [, cb]) Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/index.md Loads a single fixture document into the database using the provided Sequelize models. Returns a promise that resolves once the fixture is loaded. ```APIDOC ## loadFixture(fixture, models [, options] [, cb]) ### Description Loads a single fixture document into the database using the provided Sequelize models. Returns a promise that resolves once the fixture is loaded. ### Method loadFixture ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **fixture** (object) - Required - A single fixture document `{ model, data, keys?, buildOptions?, saveOptions?, ignoreSet? }` - **models** (object) - Required - Map of `{ [modelName]: SequelizeModel }` - **options** (object) - Optional - Configuration options, default `{}` - **cb** (function) - Optional - Deprecated callback, superseded by the returned promise ### Request Example ```js const sequelize_fixtures = require('sequelize-fixtures'); const models = require('./models'); // map of model name -> Sequelize model sequelize_fixtures .loadFixture({ model: 'Foo', data: { propA: 'bar', propB: 1 } }, models) .then(() => console.log('fixture loaded')); ``` ### Response #### Success Response (200) - **result** (promise) - Resolves with the many2many/save chain result, not the result object. #### Response Example ```js sequelize_fixtures .loadFixture({ model: 'Foo', data: { propA: 'bar' } }, models) .catch(err => { console.error('Fixture load failed:', err.message); }); ``` ``` -------------------------------- ### readFiles method definition Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/reader.md Defines the readFiles method on the Reader prototype. It takes an array of file paths and/or glob patterns, each processed through readFileGlob. Returns a promise resolving to the concatenation of all fixtures in the given order; any error rejects the whole promise. ```javascript Reader.prototype.readFiles = function(filenames){ ``` -------------------------------- ### loadFixture(fixture, models) Source: https://github.com/domasx2/sequelize-fixtures/blob/master/_autodocs/api-reference/loader.md Loads a single fixture document. Validates input synchronously, resolves the model, and processes the fixture. Throws synchronously for validation errors and rejects on model resolution failures. ```APIDOC ## loadFixture(fixture, models) ### Description Loads a single fixture document. Validates the fixture object, resolves the Sequelize model, and processes the fixture data. Returns a promise that resolves to the outcome of `setManyToMany(instance)` or `undefined`. ### Method `loadFixture(fixture, models)` ### Parameters - **fixture** (object) - Required - Fixture document with shape `{ model, data, keys?, buildOptions?, saveOptions?, ignoreSet? }`. - **models** (object) - Required - Map of `{ [modelName]: SequelizeModel }`. ### Return Promise resolving to the outcome of `setManyToMany(instance)` (an array of association-add promises) or `undefined`. The created/found instance is recorded in `this.fixtureModels`. ### Throws (synchronous) - If `typeof fixture !== 'object'`: `Error('expected fixture to be object, is ' + (typeof fixture))` - If `!fixture.model`: `Error('model for a fixture is undefined')` - If `!fixture.data`: `Error('data undefined for fixture')` ### Throws (model resolution) - If model not in `models`: logs error and throws `Error('Model not found: ' + fixture.model)` - If `typeof Model === 'function' && typeof Model.prototype !== 'object'`: throws `Error('models.' + fixture.model + ' appears to be a function. Perhaps you are importing model factory function? You should then use sequelize.import to create your model, see https://github.com/sequelize/express-example/blob/master/models/index.js#L17')` - If `!Model.findOne`: throws `Error('models.' + fixture.model + ' is not a sequelize model.')` ```