2022-01-17 23:44:08 -05:00
|
|
|
import { User, CreateUser, Users } from '@logto/schemas';
|
2021-07-02 08:14:18 -05:00
|
|
|
import { sql } from 'slonik';
|
2021-08-29 22:30:54 -05:00
|
|
|
|
|
|
|
import { buildInsertInto } from '@/database/insert-into';
|
2021-07-02 09:55:14 -05:00
|
|
|
import pool from '@/database/pool';
|
2021-11-17 22:26:34 -05:00
|
|
|
import { buildUpdateWhere } from '@/database/update-where';
|
|
|
|
import { convertToIdentifiers, OmitAutoSetFields } from '@/database/utils';
|
2022-01-13 21:19:43 -05:00
|
|
|
import { DeletionError } from '@/errors/SlonikError';
|
2021-07-02 08:14:18 -05:00
|
|
|
|
|
|
|
const { table, fields } = convertToIdentifiers(Users);
|
|
|
|
|
2021-07-26 09:32:18 -05:00
|
|
|
export const findUserByUsername = async (username: string) =>
|
2021-12-07 22:11:27 -05:00
|
|
|
pool.one<User>(sql`
|
2021-12-20 01:20:23 -05:00
|
|
|
select ${sql.join(Object.values(fields), sql`,`)}
|
|
|
|
from ${table}
|
|
|
|
where ${fields.username}=${username}
|
|
|
|
`);
|
2021-07-26 09:32:18 -05:00
|
|
|
|
2021-07-02 08:14:18 -05:00
|
|
|
export const findUserById = async (id: string) =>
|
2021-12-07 22:11:27 -05:00
|
|
|
pool.one<User>(sql`
|
2021-12-20 01:20:23 -05:00
|
|
|
select ${sql.join(Object.values(fields), sql`,`)}
|
|
|
|
from ${table}
|
|
|
|
where ${fields.id}=${id}
|
|
|
|
`);
|
2021-07-04 04:41:46 -05:00
|
|
|
|
|
|
|
export const hasUser = async (username: string) =>
|
|
|
|
pool.exists(sql`
|
2021-12-20 01:20:23 -05:00
|
|
|
select ${fields.id}
|
|
|
|
from ${table}
|
|
|
|
where ${fields.username}=${username}
|
|
|
|
`);
|
2021-07-04 04:41:46 -05:00
|
|
|
|
|
|
|
export const hasUserWithId = async (id: string) =>
|
|
|
|
pool.exists(sql`
|
2021-12-20 01:20:23 -05:00
|
|
|
select ${fields.id}
|
|
|
|
from ${table}
|
|
|
|
where ${fields.id}=${id}
|
|
|
|
`);
|
2021-07-04 04:41:46 -05:00
|
|
|
|
2022-01-17 23:44:08 -05:00
|
|
|
export const insertUser = buildInsertInto<CreateUser, User>(pool, Users, { returning: true });
|
2021-11-17 22:26:34 -05:00
|
|
|
|
|
|
|
export const findAllUsers = async () =>
|
2021-12-07 22:11:27 -05:00
|
|
|
pool.many<User>(sql`
|
2021-11-17 22:26:34 -05:00
|
|
|
select ${sql.join(Object.values(fields), sql`, `)}
|
|
|
|
from ${table}
|
|
|
|
`);
|
|
|
|
|
2022-01-17 23:44:08 -05:00
|
|
|
const updateUser = buildUpdateWhere<CreateUser, User>(pool, Users, true);
|
2021-11-17 22:26:34 -05:00
|
|
|
|
2022-01-17 23:44:08 -05:00
|
|
|
export const updateUserById = async (id: string, set: Partial<OmitAutoSetFields<CreateUser>>) =>
|
2021-11-17 22:26:34 -05:00
|
|
|
updateUser({ set, where: { id } });
|
|
|
|
|
|
|
|
export const deleteUserById = async (id: string) => {
|
|
|
|
const { rowCount } = await pool.query(sql`
|
2021-12-20 01:20:23 -05:00
|
|
|
delete from ${table}
|
|
|
|
where id=${id}
|
|
|
|
`);
|
2021-11-17 22:26:34 -05:00
|
|
|
if (rowCount < 1) {
|
2022-01-13 21:19:43 -05:00
|
|
|
throw new DeletionError();
|
2021-11-17 22:26:34 -05:00
|
|
|
}
|
|
|
|
};
|