db/seed.js
// The function form can be used to initialize rows that reference other models.
The function form can be used to initialize rows that reference other models.
The function form can be used to initialize rows that reference other models .
function seed(Model, rows) {
  return (others={}) => {
    if (typeof rows === 'function') {
      rows = Promise.props(
        mapValues(others,
          other =>
            typeof other === 'function' ? other() : other)
      ).then(rows)
    }
    return Promise.resolve(rows)
      .then(rows => Promise.props(
        Object.keys(rows)
          .map(key => {
            const row = rows[key]
            return {
              key,
              value: Promise.props(row)
                .then(row => Model.create(row)
                  .catch(error => { throw new BadRow(key, row, error) })
                )
            }
          }).reduce(
            (all, one) => Object.assign({}, all, {[one.key]: one.value}),
            {}
          )
        )
      )
      .then(seeded => {
        console.log(`Seeded ${Object.keys(seeded).length} ${Model.name} OK`)
        return seeded
      }).catch(error => {
        console.error(`Error seeding ${Model.name}: ${error} \n${error.stack}`)
      })
  }
}
function seed ( Model , rows ) { return ( others = { } ) => { if ( typeof rows === 'function' ) { rows = Promise . props ( mapValues ( others , other => typeof other === 'function' ? other ( ) : other ) ) . then ( rows ) } return Promise . resolve ( rows ) . then ( rows => Promise . props ( Object . keys ( rows ) . map ( key => { const row = rows [ key ] return { key , value : Promise . props ( row ) . then ( row => Model . create ( row ) . catch ( error => { throw new BadRow ( key , row , error ) } ) ) } } ) . reduce ( ( all , one ) => Object . assign ( { } , all , { [ one . key ] : one . value } ) , { } ) ) ) . then ( seeded => { console . log ( ` ${ Object . keys ( seeded ) . length } ${ Model . name } ` ) return seeded } ) . catch ( error => { console . error ( ` ${ Model . name } ${ error } \n ${ error . stack } ` ) } ) } }
The function form can be used to initialize rows that reference other models.
The function form can be used to initialize rows that reference other models .
// Is other a function? If so, call it. Otherwise, leave it alone.