RunKit + npm: knex

node v8.17.0
version: 4.0.1
endpointsharetweet
require('sqlite3'); // require('pg'); const Knex = require('knex'); const config = { development: { client: 'sqlite', connection: ':memory:', debug: true, }, } const k = Knex(config.development); // const k = Knex({ // client: 'pg' // }); await k.schema.createTable('User', t => { t.increments('id').primary().unsigned(); t.string('name').notNullable(); }); await k.schema.createTable('SomeObj', t => { t.increments('id').primary().unsigned(); t.integer('userId').notNullable().unsigned().index() .references('id') .inTable('User'); }); await k('User').insert([{ name: 'a1' }, { name: 'a2' }]); await k('SomeObj').insert([{ userId: 1 }, { userId: 2 }, { userId: 2 }]); const SQL = () => k('SomeObj'); const GetAll = async userId => SQL().where({ userId }).select( 'id', 'userId', ); const GetById = async (userId, id) => SQL().where({ userId, id }).first( 'id', 'userId', ); class SomeObj { constructor(data, userId) { this.userId = userId; this.id = data.id; } static async LoadAll(userId) { const data = await GetAll(userId); if (!data || data.length === 0) return null; return data.map(r => new SomeObj(r, userId)); } static async Load(userId, id) { const data = await GetById(userId, id); if (!data) return null; return new SomeObj(data, userId); } } const ReceiveRequest = async (userId, id) => { try { console.log('attempting'); const res1 = await SomeObj.LoadAll(userId); const res2 = await SomeObj.Load(userId, id); console.log(`res: ${JSON.stringify({ res1, res2 })}`); // res.json({ res1, res2 }); } catch (ex) { console.log(`error: ${JSON.stringify(ex)}`); // res.status(401).json(ex); } } await ReceiveRequest(2, 2); await ReceiveRequest(2, 1); await ReceiveRequest(2, 2); // console.log(await k('SomeObj').where({ userId: 2 }).select('*'));
Created from: https://npm.runkit.com/knex
Loading…

2 comments

  • posted 6 years ago by mikaelle
    const GetAll = async userId => SQL.where({ userId }).select( 'id', 'userId', ); You you are using the same query builder as a base for multiple queries, you need to do SQL.clone() or otherwise function just mutates the same between multiple calls.
  • posted 6 years ago by mikaelle
    This was the example works: const GetAll = async userId => SQL.clone().where({ userId }).select( 'id', 'userId', ); const GetById = async (userId, id) => SQL.clone().where({ userId, id }).first( 'id', 'userId', );

sign in to comment