import Knex from 'knex'; import config from '../knexfile'; export interface Pg { userGetId: (id: UUID) => Promise, userGetName: (name: string) => Promise, userUpsert: (user: User) => Promise, userWants: (user: User) => Promise, wantUpsert: (want: Want, user: User) => Promise, listingUpsert: (listing: Listing, want: Want) => Promise, listingGet: (id: number) => Promise, } export default function createPg(): Pg { const pg = Knex(config); async function userGetId(id): Promise { return pg('users') .where({ id }) .first(); } async function userGetName(name): Promise { return pg('users') .where({ discogs: name }) .first(); } async function userWants(user: User): Promise { return pg('wants') .where({ user: user.id }); } async function userUpsert(user): Promise { const [row] = await pg('users') .insert({ discogs: user.username, data: user, }) .onConflict('id') .merge() .onConflict('discogs') .merge() .returning('*'); return row; } async function wantUpsert(want, user): Promise { const [row] = await pg('wants') .insert({ data: want, release: want.id, user: user.id, }) .onConflict('id') .merge() .onConflict(['user', 'release']) .merge() .returning('*'); return row; } async function listingUpsert(listing, want): Promise { const [row] = await pg('listings') .insert({ id: listing.id, want: want.id, seller: listing.seller.id, data: listing, }) .onConflict('id') .merge() .returning('*'); return row; } async function listingGet(id): Promise { return pg('listings') .where({ id }) .first(); } return { userGetId, userGetName, userUpsert, userWants, wantUpsert, listingUpsert, listingGet, }; }