Database Utilities

Learn how to run queries and perform CRUD operations in your database

The useDB() composable

The useDB() composable is provided to access the database and perform CRUD operations. It's auto-imported across the project, so you can use it in any file.

index.ts
export default defineEventHandler(async (event) => {
  const userRecord = await useDB()
    .select()
    .from(tables.users)
    .where(eq(tables.users.email, email));
  return userRecord;
});

Database Actions

Supersaas organizes database actions into separate files for different entities:

  1. UserActions.js: User CRUD operations
  2. AuthActions.js: Auth CRUD operations
  3. AdminActions.js: Admin CRUD operations
  4. SubscriptionActions.js: Subscription CRUD operations
  5. ImageActions.js: Image CRUD operations
  6. PostsActions.js: Post CRUD operations

Each action file contains a class with methods for specific database operations. For example, in UserActions.js

server/services/db/UserActions.js
class UserActions {
  async findUserByEmail(email) {
    try {
      const [existingUser] = await useDB()
        .select()
        .from(tables.users)
        .where(eq(tables.users.email, email));
      return existingUser || null;
    } catch (error) {
      console.error(error);
      return null;
    }
  }

  // ... other methods
}

export const userActions = new UserActions();