0
Fork 0
mirror of https://github.com/logto-io/logto.git synced 2025-01-06 20:40:08 -05:00
logto/packages/core/src/queries/user.ts

91 lines
2.5 KiB
TypeScript
Raw Normal View History

import { User, CreateUser, Users } from '@logto/schemas';
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';
import { DeletionError } from '@/errors/SlonikError';
const { table, fields } = convertToIdentifiers(Users);
export const findUserByUsername = async (username: string) =>
pool.one<User>(sql`
select ${sql.join(Object.values(fields), sql`,`)}
from ${table}
where ${fields.username}=${username}
`);
export const findUserByEmail = async (email: string) =>
pool.one<User>(sql`
select ${sql.join(Object.values(fields), sql`,`)}
from ${table}
where ${fields.primaryEmail}=${email}
`);
export const findUserByPhone = async (phone: string) =>
pool.one<User>(sql`
select ${sql.join(Object.values(fields), sql`,`)}
from ${table}
where ${fields.primaryPhone}=${phone}
`);
export const findUserById = async (id: string) =>
pool.one<User>(sql`
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`
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`
select ${fields.id}
from ${table}
where ${fields.id}=${id}
`);
2021-07-04 04:41:46 -05:00
export const hasUserWithEmail = async (email: string) =>
pool.exists(sql`
select ${fields.primaryEmail}
from ${table}
where ${fields.primaryEmail}=${email}
`);
export const hasUserWithPhone = async (phone: string) =>
pool.exists(sql`
select ${fields.primaryPhone}
from ${table}
where ${fields.primaryPhone}=${phone}
`);
export const insertUser = buildInsertInto<CreateUser, User>(pool, Users, { returning: true });
2021-11-17 22:26:34 -05:00
export const findAllUsers = async () =>
pool.many<User>(sql`
2021-11-17 22:26:34 -05:00
select ${sql.join(Object.values(fields), sql`, `)}
from ${table}
`);
const updateUser = buildUpdateWhere<CreateUser, User>(pool, Users, true);
2021-11-17 22:26:34 -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`
delete from ${table}
where id=${id}
`);
2022-01-27 06:26:34 -05:00
2021-11-17 22:26:34 -05:00
if (rowCount < 1) {
throw new DeletionError();
2021-11-17 22:26:34 -05:00
}
};