98 lines
2.3 KiB
TypeScript
98 lines
2.3 KiB
TypeScript
import Knex from 'knex';
|
|
|
|
import config from '../knexfile';
|
|
|
|
export interface Pg {
|
|
userGetId: (id: UUID) => Promise<User>,
|
|
userGetName: (name: string) => Promise<User>,
|
|
userUpsert: (user: User) => Promise<User>,
|
|
userWants: (user: User) => Promise<Want[]>,
|
|
|
|
wantUpsert: (want: Want, user: User) => Promise<Want>,
|
|
listingUpsert: (listing: Listing, want: Want) => Promise<Listing>,
|
|
listingGet: (id: number) => Promise<Listing>,
|
|
}
|
|
|
|
export default function createPg(): Pg {
|
|
const pg = Knex(config);
|
|
|
|
async function userGetId(id): Promise<User> {
|
|
return pg('users')
|
|
.where({ id })
|
|
.first();
|
|
}
|
|
|
|
async function userGetName(name): Promise<User> {
|
|
return pg('users')
|
|
.where({ discogs: name })
|
|
.first();
|
|
}
|
|
|
|
async function userWants(user: User): Promise<Want[]> {
|
|
return pg('wants')
|
|
.where({ user: user.id });
|
|
}
|
|
|
|
async function userUpsert(user): Promise<User> {
|
|
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<Want> {
|
|
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<Listing> {
|
|
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<Listing> {
|
|
return pg('listings')
|
|
.where({ id })
|
|
.first();
|
|
}
|
|
|
|
return {
|
|
userGetId,
|
|
userGetName,
|
|
userUpsert,
|
|
userWants,
|
|
|
|
wantUpsert,
|
|
listingUpsert,
|
|
listingGet,
|
|
};
|
|
} |