require('sqlite3');
// require('pg');
const Knex = require('knex');
const config = {
development: {
client: 'sqlite',
connection: ':memory:',
},
}
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.clone().where({ userId }).select(
'id',
'userId',
);
const GetById = async (userId, id) => SQL.clone().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('*'));