Skip to content

Commit

Permalink
feat(database): add nestjs-prisma module
Browse files Browse the repository at this point in the history
  • Loading branch information
NedcloarBR committed Jul 14, 2024
1 parent 99016d3 commit 57ddad7
Show file tree
Hide file tree
Showing 20 changed files with 221 additions and 181 deletions.
5 changes: 3 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,7 @@
"@nestjs/event-emitter": "^2.0.4",
"@nestjs/platform-express": "^10.3.8",
"@nestjs/schedule": "^4.0.2",
"@prisma/client": "5.11.0",
"@prisma/client": "5.16.2",
"class-transformer": "^0.5.1",
"class-validator": "^0.14.1",
"discord-api-types": "^0.37.73",
Expand All @@ -50,8 +50,9 @@
"lavalink-client": "^2.1.7",
"moment": "^2.30.1",
"necord": "^6.8.3",
"nestjs-prisma": "^0.23.0",
"parse-ms": "=2.1.0",
"prisma": "^5.11.0",
"prisma": "^5.16.2",
"reflect-metadata": "^0.2.1",
"rxjs": "^7.8.1",
"topgg-autoposter": "^2.0.2"
Expand Down
2 changes: 2 additions & 0 deletions src/lib/index.ts
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
export * from "./node-handler";
export * from "./prisma-utils";
export * from "./sharding";
export * from "./top.gg-autoposter";
5 changes: 3 additions & 2 deletions src/lib/node-handler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@ import { Logger } from "@nestjs/common";
export function NodeHandler(): void {
const logger = new Logger("NodeHandler");
process.on("uncaughtException", (error, origin) => {
logger.error("Uncaught Exception:", error, "Origin: ", origin);
logger.error(`Uncaught Exception: ${error} | Origin: ${origin}`);
});

process.on("unhandledRejection", (reason, promise) => {
logger.error("Unhandled Rejection at:", promise, "reason:", reason);
logger.error(`Unhandled Rejection reason: ${reason} | at:`);
console.log(promise);
});
}
10 changes: 10 additions & 0 deletions src/lib/prisma-utils.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { HttpStatus } from "@nestjs/common";
import { PrismaClientExceptionFilter } from "nestjs-prisma";

export const PrismaExceptionFilter = (httpAdapter) => {
return new PrismaClientExceptionFilter(httpAdapter, {
P2000: HttpStatus.BAD_REQUEST,
P2002: HttpStatus.CONFLICT,
P2025: HttpStatus.NOT_FOUND,
});
};
2 changes: 1 addition & 1 deletion src/lib/sharding.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import path from "node:path";
import { Config } from "@/modules/config/types";
import { Logger } from "@nestjs/common";
import type { ConfigService } from "@nestjs/config";
import { ConfigService } from "@nestjs/config";
import { ShardingManager as _ShardingManager } from "discord.js";

export class ShardingManager extends _ShardingManager {
Expand Down
6 changes: 4 additions & 2 deletions src/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,19 @@ import { Logger } from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { NestFactory } from "@nestjs/core";
import { AppModule } from "./app.module";
import { ShardingManager, TopGGAutoPoster } from "./lib";
import { NodeHandler } from "./lib/node-handler";
import { NodeHandler, PrismaExceptionFilter, ShardingManager, TopGGAutoPoster } from "./lib";

async function bootstrap() {
NodeHandler();
const app = await NestFactory.create(AppModule);
const configService = app.get<ConfigService>(ConfigService);
const httpAdapter = app.getHttpAdapter();
const logger = new Logger("Main");
const ShardManager = new ShardingManager(configService);
const TopGGPoster = new TopGGAutoPoster(configService.getOrThrow("TopGGToken"), ShardManager);

app.useGlobalFilters(PrismaExceptionFilter(httpAdapter));

try {
await ShardManager.init();
await TopGGPoster.init();
Expand Down
17 changes: 0 additions & 17 deletions src/modules/database/als/als.module.ts

This file was deleted.

15 changes: 0 additions & 15 deletions src/modules/database/als/als.service.ts

This file was deleted.

4 changes: 0 additions & 4 deletions src/modules/database/als/interfaces/IAsyncLocalStorage.ts

This file was deleted.

3 changes: 0 additions & 3 deletions src/modules/database/als/types/index.ts

This file was deleted.

16 changes: 13 additions & 3 deletions src/modules/database/database.module.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { Services } from "@/types/Constants";
import { Global, Module, Provider } from "@nestjs/common";
import { AlsModule } from "./als/als.module";
import { PrismaModule } from "nestjs-prisma";
import { DatabaseService } from "./database.service";
import { PrismaModule } from "./prisma/Prisma.module";
import { RepositoriesModule } from "./repositories/Repositories.module";

const provider: Provider<DatabaseService> = {
Expand All @@ -12,7 +11,18 @@ const provider: Provider<DatabaseService> = {

@Global()
@Module({
imports: [AlsModule, RepositoriesModule, PrismaModule],
imports: [
PrismaModule.forRootAsync({
isGlobal: true,
useFactory: () => ({
prismaOptions: {
log: ["info"],
},
explicitConnect: false,
}),
}),
RepositoriesModule,
],
providers: [provider],
exports: [provider],
})
Expand Down
6 changes: 0 additions & 6 deletions src/modules/database/database.service.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,18 @@
import type { IReactionRolesRepository } from "@/modules/reactionRoles/interfaces/IReactionRoleRepository";
import { ReactionRoles } from "@/modules/reactionRoles/types/constants";
import { Inject, Injectable } from "@nestjs/common";
import type { IAsyncLocalStorage } from "./als/interfaces/IAsyncLocalStorage";
import type { IDatabaseService } from "./interfaces/IDatabaseService";
import type { IGuildRepository, IUserRepository } from "./repositories/interfaces";
import { Repositories } from "./types/constants";

@Injectable()
export class DatabaseService implements IDatabaseService {
public constructor(
@Inject(Repositories.ALS) private readonly als: IAsyncLocalStorage,
@Inject(Repositories.Guild) private readonly guild: IGuildRepository,
@Inject(Repositories.User) private readonly user: IUserRepository,
@Inject(ReactionRoles.Repository) private readonly reactionRoles: IReactionRolesRepository,
) {}

public AlsRepo(): IAsyncLocalStorage {
return this.als;
}

public GuildRepo(): IGuildRepository {
return this.guild;
}
Expand Down
2 changes: 0 additions & 2 deletions src/modules/database/interfaces/IDatabaseService.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
import type { IReactionRolesRepository } from "@/modules/reactionRoles/interfaces";
import type { IAsyncLocalStorage } from "../als/interfaces/IAsyncLocalStorage";
import type { IGuildRepository } from "../repositories/interfaces/IGuildRepository";
import type { IUserRepository } from "../repositories/interfaces/IUserRepository";

export interface IDatabaseService {
AlsRepo(): IAsyncLocalStorage;
GuildRepo(): IGuildRepository;
UserRepo(): IUserRepository;
ReactionRolesRepo(): IReactionRolesRepository;
Expand Down
15 changes: 0 additions & 15 deletions src/modules/database/prisma/Prisma.module.ts

This file was deleted.

29 changes: 0 additions & 29 deletions src/modules/database/prisma/Prisma.service.ts

This file was deleted.

17 changes: 8 additions & 9 deletions src/modules/database/repositories/Guild.repository.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,21 @@
import { Services } from "@/types/Constants";
import { Inject, Injectable, Logger } from "@nestjs/common";
import { Injectable, Logger } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { DefaultArgs } from "@prisma/client/runtime/library";
import { Guild } from "discord.js";
import { PrismaService } from "nestjs-prisma";
import { GuildEntity } from "../entities";
import { PrismaService } from "../prisma/Prisma.service";
import { DatabaseStatus } from "../types";
import type { IGuildRepository } from "./interfaces";
import { DefaultArgs } from "@prisma/client/runtime/library";
import { Prisma } from "@prisma/client";

@Injectable()
export class GuildRepository implements IGuildRepository {
public constructor(@Inject(Services.Prisma) private readonly prisma: PrismaService) {}
public constructor(private readonly prisma: PrismaService) {}

private readonly logger = new Logger(GuildRepository.name);

public guildSettings(): Prisma.GuildSettingsDelegate<DefaultArgs> {
return this.prisma.guildSettings
}
public guildSettings(): Prisma.GuildSettingsDelegate<DefaultArgs> {
return this.prisma.guildSettings;
}

public async get(guildId: string): Promise<GuildEntity> {
return await this.prisma.guild.findUnique({
Expand Down
29 changes: 14 additions & 15 deletions src/modules/database/repositories/User.repository.ts
Original file line number Diff line number Diff line change
@@ -1,21 +1,20 @@
import { Services } from "@/types/Constants";
import { Inject, Logger } from "@nestjs/common";
import { Logger } from "@nestjs/common";
import { Prisma } from "@prisma/client";
import { DefaultArgs } from "@prisma/client/runtime/library";
import { User } from "discord.js";
import { PrismaService } from "nestjs-prisma";
import { UserEntity } from "../entities";
import { PrismaService } from "../prisma/Prisma.service";
import { DatabaseStatus } from "../types";
import type { IUserRepository } from "./interfaces";
import { Prisma } from "@prisma/client";
import { DefaultArgs } from "@prisma/client/runtime/library";
import { IUserRepository } from "./interfaces";

export class UserRepository implements IUserRepository {
public constructor(@Inject(Services.Prisma) private readonly prisma: PrismaService) {}
public constructor(private readonly prisma: PrismaService) {}

private readonly logger = new Logger(UserRepository.name);

public userSettings(): Prisma.UserSettingsDelegate<DefaultArgs> {
return this.prisma.userSettings
}
public userSettings(): Prisma.UserSettingsDelegate<DefaultArgs> {
return this.prisma.userSettings;
}

public async get(userId: string): Promise<UserEntity> {
return await this.prisma.user.findUnique({
Expand All @@ -27,14 +26,14 @@ export class UserRepository implements IUserRepository {
});
}

public async getAll(): Promise<UserEntity[]> {
return await this.prisma.user.findMany({
public async getAll(): Promise<UserEntity[]> {
return await this.prisma.user.findMany({
include: {
Settings: true,
APIUser: true,
Settings: true,
},
});
}
}

public async create(user: User): Promise<{ callback: UserEntity | void; status: DatabaseStatus }> {
let status = DatabaseStatus.Created;
Expand Down
21 changes: 6 additions & 15 deletions src/modules/reactionRoles/ReactionRoles.repository.ts
Original file line number Diff line number Diff line change
@@ -1,14 +1,13 @@
import type { PrismaService } from "@/modules/database/prisma/Prisma.service";
import { Services } from "@/types/Constants";
import { Inject, Injectable } from "@nestjs/common";
import { Injectable } from "@nestjs/common";
import type { Guild, TextChannel } from "discord.js";
import { PrismaService } from "nestjs-prisma";
import type { ReactionRolesEntity } from "./entities/ReactionRole.entity";
import type { IReactionRolesRepository } from "./interfaces/IReactionRoleRepository";
import type { IReaction, REACTION_OPTIONS } from "./types";

@Injectable()
export class ReactionRolesRepository implements IReactionRolesRepository {
public constructor(@Inject(Services.Prisma) private readonly prisma: PrismaService) {}
public constructor(private readonly prisma: PrismaService) {}

public async getAll(guild: Guild): Promise<ReactionRolesEntity[]> {
return await this.prisma.guildReactionRoles.findMany({
Expand All @@ -30,18 +29,12 @@ export class ReactionRolesRepository implements IReactionRolesRepository {
})[0];
}

public async getInChannel(
guild: Guild,
channel: TextChannel,
): Promise<ReactionRolesEntity[]> {
public async getInChannel(guild: Guild, channel: TextChannel): Promise<ReactionRolesEntity[]> {
const data = await this.getAll(guild);
return data.filter(async (reaction) => reaction.Channel === channel.id);
}

private async checkIfExists(
guild: Guild,
{ Channel, Message, Role, Emoji, Option }: IReaction,
): Promise<boolean> {
private async checkIfExists(guild: Guild, { Channel, Message, Role, Emoji, Option }: IReaction): Promise<boolean> {
const GetGuild = await this.getAll(guild);
let Verify = false;
for (const reaction of GetGuild) {
Expand Down Expand Up @@ -124,9 +117,7 @@ export class ReactionRolesRepository implements IReactionRolesRepository {
return { status: "Deleted" };
}

public async deleteMany(
guild: Guild,
): Promise<{ status: "UnableToDelete" | "Deleted"; count: number }> {
public async deleteMany(guild: Guild): Promise<{ status: "UnableToDelete" | "Deleted"; count: number }> {
const count = await this.prisma.guildReactionRoles.count({
where: { guildId: guild.id },
});
Expand Down
1 change: 0 additions & 1 deletion src/types/Constants.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ export const isInProduction = false;

export enum Services {
NDB = "NDB_SERVICE",
Prisma = "PRISMA_SERVICE",
Database = "DATABASE_SERVICE",
User = "USER_SERVICE",
Auth = "AUTH_SERVICE",
Expand Down
Loading

0 comments on commit 57ddad7

Please sign in to comment.