node-sql-fixtures icon indicating copy to clipboard operation
node-sql-fixtures copied to clipboard

example using knex:seed

Open machinshin opened this issue 7 years ago • 4 comments

I just found this library. If I understand it right, I should be able to use use it inside a knex seed to create my test rows.. It would be nice if there was an example on using sql-fixtures from inside the seed function. (i might have time next weekend to this myself)

machinshin avatar Jun 27 '17 19:06 machinshin

Sorry for the late reply, for some reason I was no longer watching this repo.

Yeah, sql-fixtures should be usable inside seeds. I'll try to carve out some time to explore an example

city41 avatar Jan 07 '18 22:01 city41

Allow me to jump in the conversation with the following example:

Supposedly we have the following folder structure:

seeds/index.js
seeds/foos.json
seeds/bars.json
...
// seed/index.js
const path = require('path');
const glob = require('glob');
const sqlFixtures = require('sql-fixtures');

function promosifiedGlob(expression, options) {
  return new Promise((resolve, reject) => {
    glob(expression, options, (e, files) => {
      if (e) {
        reject(e);
      }
      resolve(files);
    });
  });
}

exports.seed = function(knex, Promise) {
  const fixtureCreator = new sqlFixtures(knex);

  return promosifiedGlob(`${__dirname}/**/*.json`)
    .then(files => {
      return Promise.all(files.map(file => {
        console.log(`Populating ${file}...`);
        const table = path.basename(file, '.json');
        const data = require(path.resolve(file));
        return fixtureCreator.create({ [table]: data });
      }));
    })
    .then(function () {
      console.log('🥁 Done!');
    })
    .catch(function (err) {
      console.error(`💣 Error: ${err.message || err}`);
    });
};

The only nit-picky drawback is the fact that knex seeds outputs Ran 1 seed files index.js.

SokratisVidros avatar Mar 14 '18 16:03 SokratisVidros

This is great @SokratisVidros! At some point I'll grab this and add it to the docs.

city41 avatar Mar 14 '18 16:03 city41

Thanks a lot @city41

SokratisVidros avatar Mar 14 '18 16:03 SokratisVidros