Skip to content

Instantly share code, notes, and snippets.

@danielrearden
Last active July 20, 2017 19:17
Show Gist options
  • Save danielrearden/ff6b592378be1508bca6efae46329c9d to your computer and use it in GitHub Desktop.
Save danielrearden/ff6b592378be1508bca6efae46329c9d to your computer and use it in GitHub Desktop.
createMockRow
const chance = require('chance')
module.exports = (db, table, specificProps) => db.raw(`
SELECT column_name, data_type
FROM information_schema.columns
WHERE table_name = '${table}';
`).then((cols) => cols.reduce((memo, col) => {
switch (col.data_type) {
case 'uuid': return Object.assign({ [col.column_name]: chance.guid() }, memo);
case 'character varying': return Object.assign({ [col.column_name]: chance.word() }, memo);
case 'text': return Object.assign({ [col.column_name]: chance.sentence() }, memo);
case 'boolean': return Object.assign({ [col.column_name]: chance.bool() }, memo);
case 'int': return Object.assign({ [col.column_name]: chance.integer() }, memo);
case 'USER-DEFINED': return Object.assign({ [col.column_name]: chance.word() }, memo);
case 'tstzrange': return Object.assign({ [col.column_name]: '["-infinity","infinity")' }, memo);
case 'jsonb': return Object.assign({ [col.column_name]: JSON.stringify({}) }, memo);
default: return memo);
}
}, {}))
.then((obj) => Object.assign(obj, specificProps))
.then((obj) => db(table).insert(obj).returning('*'))
.then(([row]) => {
const deleteMe = () => db(table).del().where('id', row.id)
return Object.assign({ deleteMe }, row))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment