Skip to content

Instantly share code, notes, and snippets.

@hyzyla
Last active December 15, 2023 20:24
Show Gist options
  • Save hyzyla/b075752e2b53467bf3b48daa27078ddc to your computer and use it in GitHub Desktop.
Save hyzyla/b075752e2b53467bf3b48daa27078ddc to your computer and use it in GitHub Desktop.
Controller + Service + Repository pattern with DrizzleORM
export class ActionService {
constructor(private actionReposiory: ActionReposiory) {
this.actionReposiory = actionReposiory;
}
async createAction(dto: any) {
return await this.actionReposiory.createAction(dto);
}
}
export class ActionReposiory {
async createAction(dto: any) {
return await db.insert(Action).values(dto).returning().execute();
}
}
export const Action = pgTable("actions", {
id: integer("id").primaryKey().notNull(),
userId: integer("user_id").notNull(),
});
export const client = postgres(envs.POSTGRES_URL);
export const db = drizzle(client);
const userReposiory = new UserReposiory();
const actionReposiory = new ActionReposiory();
const userService = new UserService(userReposiory);
const actionService = new ActionService(actionReposiory);
const userController = new UserController(userService, actionService);
export class UserController {
constructor(private userService: UserService, private actionService: ActionService) {
this.userService = userService;
this.actionService = actionService;
}
async createUser(dto: any) {
await db.transaction(async () => {
const user = await this.userService.createUser(dto);
const action = await this.actionService.createAction({ userId: user.id, type: "createUser" });
return { user, action };
});
}
}
export class UserReposiory {
async createUser(dto: any) {
return await db.insert(User).values(dto).returning().execute();
}
}
export const User = pgTable("users", {
id: integer("id").primaryKey().notNull(),
});
export class UserService {
constructor(private userReposiory: UserReposiory) {
this.userReposiory = userReposiory;
}
async createUser(dto: any) {
return await this.userReposiory.createUser(dto);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment