Friday, 22 May 2020

Node x SQL with Knex

Knex is very easy/simple to use and allows you to benefit of all the good things from relational databases.I wanted to share this snippet with you :)Required to run the following code: a database with a table users(id SERIAL, name VARCHAR)const knex = require('knex')({ client: 'postgres', connection: 'postgres://postgres:postgres@localhost:5432/something' }) const UserRepository = (trx) => ({ all: () => trx('users').select('name'), insert: ({ name }) => trx('users').insert({ name }), first: () => trx('users').where({ id: 1 }).select('name') }) const withTransaction = ([...repositories], transaction) => { return knex.transaction((trx) => { const transactionalRepositories = repositories.map((r) => r(trx)) return transaction(transactionalRepositories) }) } module.exports = async () => { return withTransaction([ UserRepository ], async ([ userRepository ]) => { await userRepository.insert({ name: require('faker').name.findName() }) const all = await userRepository.all() const first = await userRepository.first() return { all, first } }) }

Submitted May 22, 2020 at 05:29PM by joeyrogues

No comments:

Post a Comment