|
| 1 | +import db from './db' |
| 2 | +import { Challenge } from '../challenges/types' |
| 3 | +import { User } from './users' |
| 4 | +import { ExtractQueryType } from './util' |
| 5 | + |
| 6 | +export interface Attempt { |
| 7 | + id: string; |
| 8 | + challengeid: Challenge['id']; |
| 9 | + userid: User['id']; |
| 10 | + submission: string; |
| 11 | + createdat: Date; |
| 12 | +} |
| 13 | + |
| 14 | +export const getAllAttempts = (): Promise<Attempt[]> => { |
| 15 | + return db.query<Attempt>('SELECT * FROM attempts ORDER BY createdat ASC') |
| 16 | + .then(res => res.rows) |
| 17 | +} |
| 18 | + |
| 19 | +export const getAttemptsByUserId = ({ userid }: Pick<Attempt, 'userid'>): Promise<Attempt[]> => { |
| 20 | + return db.query<Attempt>('SELECT * FROM attempts WHERE userid = $1 ORDER BY createdat DESC', [userid]) |
| 21 | + .then(res => res.rows) |
| 22 | +} |
| 23 | + |
| 24 | +export const getAttemptsByChallId = ({ challengeid, limit, offset }: Pick<Attempt, 'challengeid'> & { limit: number; offset: number; }): Promise<(Attempt & Pick<User, 'name'>)[]> => { |
| 25 | + return db.query<ExtractQueryType<typeof getAttemptsByChallId>>('SELECT attempts.id, attempts.userid, attempts.submissions, attempts.createdat, users.name FROM attempts INNER JOIN users ON attempts.userid = users.id WHERE attempts.challengeid=$1 ORDER BY attempts.createdat ASC LIMIT $2 OFFSET $3', [challengeid, limit, offset]) |
| 26 | + .then(res => res.rows) |
| 27 | +} |
| 28 | + |
| 29 | +export const getAttemptByUserIdAndChallId = ({ userid, challengeid }: Pick<Attempt, 'userid' | 'challengeid'>): Promise<Attempt | undefined> => { |
| 30 | + return db.query<Attempt>('SELECT * FROM attempts WHERE userid = $1 AND challengeid = $2 ORDER BY createdat DESC', [userid, challengeid]) |
| 31 | + .then(res => res.rows[0]) |
| 32 | +} |
| 33 | + |
| 34 | +export const newAttempt = ({ id, userid, challengeid, submission, createdat }: Attempt): Promise<Attempt> => { |
| 35 | + return db.query<Attempt>('INSERT INTO attempts (id, challengeid, userid, submission, createdat) VALUES ($1, $2, $3, $4, $5) RETURNING *', [id, challengeid, userid, submission, createdat]) |
| 36 | + .then(res => res.rows[0]) |
| 37 | +} |
| 38 | + |
| 39 | +export const removeAttemptsByUserId = async ({ userid }: Pick<Attempt, 'userid'>): Promise<void> => { |
| 40 | + await db.query('DELETE FROM attempts WHERE userid = $1', [userid]) |
| 41 | +} |
0 commit comments