mirror of
https://github.com/logto-io/logto.git
synced 2025-01-06 20:40:08 -05:00
66 lines
1.8 KiB
TypeScript
66 lines
1.8 KiB
TypeScript
import { UserDBEntry, Users } from '@logto/schemas';
|
|
import { sql } from 'slonik';
|
|
|
|
import { buildInsertInto } from '@/database/insert-into';
|
|
import pool from '@/database/pool';
|
|
import { buildUpdateWhere } from '@/database/update-where';
|
|
import { convertToIdentifiers, OmitAutoSetFields } from '@/database/utils';
|
|
import RequestError from '@/errors/RequestError';
|
|
|
|
const { table, fields } = convertToIdentifiers(Users);
|
|
|
|
export const findUserByUsername = async (username: string) =>
|
|
pool.one<UserDBEntry>(sql`
|
|
select ${sql.join(Object.values(fields), sql`,`)}
|
|
from ${table}
|
|
where ${fields.username}=${username}
|
|
`);
|
|
|
|
export const findUserById = async (id: string) =>
|
|
pool.one<UserDBEntry>(sql`
|
|
select ${sql.join(Object.values(fields), sql`,`)}
|
|
from ${table}
|
|
where ${fields.id}=${id}
|
|
`);
|
|
|
|
export const hasUser = async (username: string) =>
|
|
pool.exists(sql`
|
|
select ${fields.id}
|
|
from ${table}
|
|
where ${fields.username}=${username}
|
|
`);
|
|
|
|
export const hasUserWithId = async (id: string) =>
|
|
pool.exists(sql`
|
|
select ${fields.id}
|
|
from ${table}
|
|
where ${fields.id}=${id}
|
|
`);
|
|
|
|
export const insertUser = buildInsertInto<UserDBEntry>(pool, Users, { returning: true });
|
|
|
|
export const findAllUsers = async () =>
|
|
pool.many<UserDBEntry>(sql`
|
|
select ${sql.join(Object.values(fields), sql`, `)}
|
|
from ${table}
|
|
`);
|
|
|
|
const updateUser = buildUpdateWhere<UserDBEntry>(pool, Users, true);
|
|
|
|
export const updateUserById = async (id: string, set: Partial<OmitAutoSetFields<UserDBEntry>>) =>
|
|
updateUser({ set, where: { id } });
|
|
|
|
export const deleteUserById = async (id: string) => {
|
|
const { rowCount } = await pool.query(sql`
|
|
delete from ${table}
|
|
where id=${id}
|
|
`);
|
|
if (rowCount < 1) {
|
|
throw new RequestError({
|
|
code: 'entity.not_exists_with_id',
|
|
name: Users.tableSingular,
|
|
id,
|
|
status: 404,
|
|
});
|
|
}
|
|
};
|