2022-11-25 19:24:05 +03:30
|
|
|
import { v4 as uuid } from "uuid";
|
2020-01-30 18:51:52 +03:30
|
|
|
import { addMinutes } from "date-fns";
|
|
|
|
|
2022-11-25 19:24:05 +03:30
|
|
|
import redisCLient, * as redis from "../redis";
|
2020-01-30 18:51:52 +03:30
|
|
|
import knex from "../knex";
|
|
|
|
|
|
|
|
export const find = async (match: Partial<User>) => {
|
|
|
|
if (match.email || match.apikey) {
|
|
|
|
const key = redis.key.user(match.email || match.apikey);
|
2022-11-25 19:24:05 +03:30
|
|
|
const cachedUser = await redisCLient.get(key);
|
2020-01-30 18:51:52 +03:30
|
|
|
if (cachedUser) return JSON.parse(cachedUser) as User;
|
|
|
|
}
|
|
|
|
|
2022-11-25 19:24:05 +03:30
|
|
|
const user = await knex<User>("users").where(match).first();
|
2020-01-30 18:51:52 +03:30
|
|
|
|
|
|
|
if (user) {
|
|
|
|
const emailKey = redis.key.user(user.email);
|
2022-11-25 19:24:05 +03:30
|
|
|
redisCLient.set(emailKey, JSON.stringify(user), "EX", 60 * 60 * 1);
|
2020-01-30 18:51:52 +03:30
|
|
|
|
|
|
|
if (user.apikey) {
|
|
|
|
const apikeyKey = redis.key.user(user.apikey);
|
2022-11-25 19:24:05 +03:30
|
|
|
redisCLient.set(apikeyKey, JSON.stringify(user), "EX", 60 * 60 * 1);
|
2020-01-30 18:51:52 +03:30
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
return user;
|
|
|
|
};
|
|
|
|
|
|
|
|
interface Add {
|
|
|
|
email: string;
|
|
|
|
password: string;
|
|
|
|
}
|
|
|
|
|
|
|
|
export const add = async (params: Add, user?: User) => {
|
|
|
|
const data = {
|
|
|
|
email: params.email,
|
|
|
|
password: params.password,
|
|
|
|
verification_token: uuid(),
|
|
|
|
verification_expires: addMinutes(new Date(), 60).toISOString()
|
|
|
|
};
|
|
|
|
|
|
|
|
if (user) {
|
|
|
|
await knex<User>("users")
|
|
|
|
.where("id", user.id)
|
|
|
|
.update({ ...data, updated_at: new Date().toISOString() });
|
|
|
|
} else {
|
|
|
|
await knex<User>("users").insert(data);
|
|
|
|
}
|
|
|
|
|
|
|
|
redis.remove.user(user);
|
|
|
|
|
|
|
|
return {
|
|
|
|
...user,
|
|
|
|
...data
|
|
|
|
};
|
|
|
|
};
|
|
|
|
|
|
|
|
export const update = async (match: Match<User>, update: Partial<User>) => {
|
|
|
|
const query = knex<User>("users");
|
|
|
|
|
|
|
|
Object.entries(match).forEach(([key, value]) => {
|
|
|
|
query.andWhere(key, ...(Array.isArray(value) ? value : [value]));
|
|
|
|
});
|
|
|
|
|
|
|
|
const users = await query.update(
|
|
|
|
{ ...update, updated_at: new Date().toISOString() },
|
|
|
|
"*"
|
|
|
|
);
|
|
|
|
|
|
|
|
users.forEach(redis.remove.user);
|
|
|
|
|
|
|
|
return users;
|
|
|
|
};
|
2020-02-15 16:56:06 +03:30
|
|
|
|
|
|
|
export const remove = async (user: User) => {
|
2022-11-25 19:24:05 +03:30
|
|
|
const deletedUser = await knex<User>("users").where("id", user.id).delete();
|
2020-02-15 16:56:06 +03:30
|
|
|
|
|
|
|
redis.remove.user(user);
|
|
|
|
|
|
|
|
return !!deletedUser;
|
|
|
|
};
|