user.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import { v4 as uuid } from "uuid";
  2. import { addMinutes } from "date-fns";
  3. import redisCLient, * as redis from "../redis";
  4. import knex from "../knex";
  5. export const find = async (match: Partial<User>) => {
  6. if (match.email || match.apikey) {
  7. const key = redis.key.user(match.email || match.apikey);
  8. const cachedUser = await redisCLient.get(key);
  9. if (cachedUser) return JSON.parse(cachedUser) as User;
  10. }
  11. const user = await knex<User>("users").where(match).first();
  12. if (user) {
  13. const emailKey = redis.key.user(user.email);
  14. redisCLient.set(emailKey, JSON.stringify(user), "EX", 60 * 60 * 1);
  15. if (user.apikey) {
  16. const apikeyKey = redis.key.user(user.apikey);
  17. redisCLient.set(apikeyKey, JSON.stringify(user), "EX", 60 * 60 * 1);
  18. }
  19. }
  20. return user;
  21. };
  22. interface Add {
  23. email: string;
  24. password: string;
  25. }
  26. export const add = async (params: Add, user?: User) => {
  27. const data = {
  28. email: params.email,
  29. password: params.password,
  30. verification_token: uuid(),
  31. verification_expires: addMinutes(new Date(), 60).toISOString()
  32. };
  33. if (user) {
  34. await knex<User>("users")
  35. .where("id", user.id)
  36. .update({ ...data, updated_at: new Date().toISOString() });
  37. } else {
  38. await knex<User>("users").insert(data);
  39. }
  40. redis.remove.user(user);
  41. return {
  42. ...user,
  43. ...data
  44. };
  45. };
  46. export const update = async (match: Match<User>, update: Partial<User>) => {
  47. const query = knex<User>("users");
  48. Object.entries(match).forEach(([key, value]) => {
  49. query.andWhere(key, ...(Array.isArray(value) ? value : [value]));
  50. });
  51. const users = await query.update(
  52. { ...update, updated_at: new Date().toISOString() },
  53. "*"
  54. );
  55. users.forEach(redis.remove.user);
  56. return users;
  57. };
  58. export const remove = async (user: User) => {
  59. const deletedUser = await knex<User>("users").where("id", user.id).delete();
  60. redis.remove.user(user);
  61. return !!deletedUser;
  62. };