Advertisement
djbob2000

Untitled

Jul 30th, 2024 (edited)
262
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // schema.ts =========================================
  2. import { pgTable, text, varchar } from 'drizzle-orm/pg-core';
  3.  
  4. export const roles = pgTable('roles', {
  5.   id: text('id').primaryKey(),
  6.   name: varchar('name', { length: 255 }).notNull(),
  7. });
  8.  
  9. export const userRoles = pgTable('user_roles', {
  10.   userId: text('user_id').notNull(),
  11.   roleId: text('role_id').notNull(),
  12. });
  13.  
  14. // role-db.ts =======================================
  15. import { eq } from 'drizzle-orm';
  16. import { roles, userRoles } from './schema';
  17. import { db } from './db';
  18. import { create } from "../exceptions/exceptions";
  19.  
  20.  
  21. export async function getAllIncludingUserToRoles(throwIfNotFound: boolean = true) {
  22.   let resources = await db.select()
  23.     .from(roles)
  24.     .leftJoin(userRoles, eq(roles.id, userRoles.roleId))
  25.     .execute();
  26.  
  27.   if (throwIfNotFound && resources.length === 0) {
  28.     throw create(`No roles were found including user roles`);
  29.   }
  30.  
  31.   return resources;
  32. }
  33.  
  34. export async function anyRoleExists() {
  35.   const result = await db.select({ count: sql`count(*)` })
  36.     .from(roles)
  37.     .execute();
  38.   return result[0].count > 0;
  39. }
  40.  
  41. export async function getAll() {
  42.   return db.select().from(roles).execute();
  43. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement