Skip to content

Instantly share code, notes, and snippets.

@veryspry
Last active July 30, 2021 13:47
Show Gist options
  • Save veryspry/6f890553473c0fa8f6d98783bd64dfaa to your computer and use it in GitHub Desktop.
Save veryspry/6f890553473c0fa8f6d98783bd64dfaa to your computer and use it in GitHub Desktop.
const postgresRecordCreator = async ({ tableName, item }) => {
const [res] = await knex(tableName)
.insert(item)
// return all fields of the newly created db record
.returning(['id', ...Object.keys(item)]);
return res;
}
const sqLiteRecordCreator = async ({ tableName, item }) => {
const [id] = await knex(tableName)
.insert(item);
const [res] = await knex(tableName)
.where('id', id);
return res;
};
/**
* Given a table name and object to store in a database, returns a function
* that will store the item and return the stored item from the database with
* all fields.
*
* This is useful since knex's API slightly differs between sqlite and postgress
*
* @param {object} config
* @returns {fn}
*/
const recordCreator = ({ tableName, item }) => {
const accessorFn = process.env.NODE_ENV === 'production'
? postgresRecordCreator
: sqLiteRecordCreator;
return accessorFn({ tableName, item });
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment