fix: fix.env.example

This commit is contained in:
rafiarrafif
2025-06-14 15:05:20 +07:00
parent b52f1202eb
commit ac10ae14f6
75 changed files with 2532 additions and 2532 deletions

View File

@ -1,7 +1,7 @@
node_modules node_modules
dist dist
.git .git
.gitignore .gitignore
Dockerfile* Dockerfile*
docker-compose* docker-compose*
README.md README.md

View File

@ -33,4 +33,4 @@ REDIS_PASSWORD=
DATABASE_URL= DATABASE_URL=
MONGODB_URI= MONGODB_URI=
# CREATE USER astofo WITH PASSWORD 'Nahidamylover*123'; #

104
.gitignore vendored
View File

@ -1,53 +1,53 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files. # See https://help.github.com/articles/ignoring-files/ for more about ignoring files.
# dependencies # dependencies
/node_modules /node_modules
/.pnp /.pnp
.pnp.js .pnp.js
# testing # testing
/coverage /coverage
# production # production
/dist /dist
/build /build
# misc # misc
.DS_Store .DS_Store
*.pem *.pem
# debug # debug
npm-debug.log* npm-debug.log*
yarn-debug.log* yarn-debug.log*
yarn-error.log* yarn-error.log*
# local env files # local env files
.env.local .env.local
.env.development.local .env.development.local
.env.test.local .env.test.local
.env.production.local .env.production.local
# vercel # vercel
.vercel .vercel
**/*.trace **/*.trace
**/*.zip **/*.zip
**/*.tar.gz **/*.tar.gz
**/*.tgz **/*.tgz
**/*.log **/*.log
package-lock.json package-lock.json
**/*.bun **/*.bun
# local env files # local env files
.env .env
.env.local .env.local
.env.development .env.development
.env.test .env.test
.env.production .env.production
# local docker compose files # local docker compose files
docker-compose.override.yml docker-compose.override.yml
# compiled output # compiled output
server server
server.exe server.exe

View File

@ -1,24 +1,24 @@
# --- Stage 1: Build --- # --- Stage 1: Build ---
FROM oven/bun:1.1 AS builder FROM oven/bun:1.1 AS builder
WORKDIR /app WORKDIR /app
COPY bun.lockb package.json ./ COPY bun.lockb package.json ./
RUN bun install RUN bun install
COPY . . COPY . .
RUN bunx prisma generate RUN bunx prisma generate
RUN bun run build RUN bun run build
# --- Stage 2: Production Runner --- # --- Stage 2: Production Runner ---
FROM oven/bun:1.1 AS runner FROM oven/bun:1.1 AS runner
WORKDIR /app WORKDIR /app
COPY --from=builder /app ./ COPY --from=builder /app ./
RUN bunx prisma migrate deploy RUN bunx prisma migrate deploy
EXPOSE 3000 EXPOSE 3000
CMD [ "sh", "-c", "PORT=3000 ./dist/server" ] CMD [ "sh", "-c", "PORT=3000 ./dist/server" ]

View File

@ -1,15 +1,15 @@
# Elysia with Bun runtime # Elysia with Bun runtime
## Getting Started ## Getting Started
To get started with this template, simply paste this command into your terminal: To get started with this template, simply paste this command into your terminal:
```bash ```bash
bun create elysia ./elysia-example bun create elysia ./elysia-example
``` ```
## Development ## Development
To start the development server run: To start the development server run:
```bash ```bash
bun run dev bun run dev
``` ```
Open http://localhost:3000/ with your browser to see the result. Open http://localhost:3000/ with your browser to see the result.

BIN
bun.lockb

Binary file not shown.

View File

@ -1,24 +1,24 @@
services: services:
app: app:
build: build:
context: . context: .
dockerfile: Dockerfile dockerfile: Dockerfile
ports: ports:
- "3003:3000" - "3003:3000"
depends_on: depends_on:
- db - db
- redis - redis
restart: unless-stopped restart: unless-stopped
db: db:
image: postgres:16-alpine image: postgres:16-alpine
volumes: volumes:
- pgdata:/var/lib/postgresql/data - pgdata:/var/lib/postgresql/data
restart: unless-stopped restart: unless-stopped
redis: redis:
image: redis:7.2-alpine image: redis:7.2-alpine
restart: unless-stopped restart: unless-stopped
volumes: volumes:
pgdata: pgdata:

File diff suppressed because it is too large Load Diff

View File

@ -1,52 +1,52 @@
import fs from "fs"; import fs from "fs";
import path from "path"; import path from "path";
const PRESERVED_KEYS = [ const PRESERVED_KEYS = [
"APP_NAME", "APP_NAME",
"APP_ENV", "APP_ENV",
"PORT", "PORT",
"API_KEY", "API_KEY",
"ALLOWED_ORIGINS", "ALLOWED_ORIGINS",
"REDIS_HOST", "REDIS_HOST",
"REDIS_PORT", "REDIS_PORT",
]; ];
try { try {
const envPath = path.join(process.cwd(), ".env"); const envPath = path.join(process.cwd(), ".env");
const envExamplePath = path.join(process.cwd(), ".env.example"); const envExamplePath = path.join(process.cwd(), ".env.example");
if (!fs.existsSync(envPath)) { if (!fs.existsSync(envPath)) {
console.error(`.env file not found at ${envPath}`); console.error(`.env file not found at ${envPath}`);
process.exit(1); process.exit(1);
} }
const envContent = fs.readFileSync(envPath, "utf-8"); const envContent = fs.readFileSync(envPath, "utf-8");
const lines = envContent.split("\n"); const lines = envContent.split("\n");
const processedLines = lines.map((line) => { const processedLines = lines.map((line) => {
const trimmedLine = line.trim(); const trimmedLine = line.trim();
if (trimmedLine.startsWith("#") || trimmedLine === "") { if (trimmedLine.startsWith("#") || trimmedLine === "") {
return line; return line;
} }
const delimeterIndex = line.indexOf("="); const delimeterIndex = line.indexOf("=");
if (delimeterIndex === -1) { if (delimeterIndex === -1) {
return line; return line;
} }
const key = line.substring(0, delimeterIndex).trim(); const key = line.substring(0, delimeterIndex).trim();
const value = line.substring(delimeterIndex + 1).trim(); const value = line.substring(delimeterIndex + 1).trim();
if (PRESERVED_KEYS.includes(key)) { if (PRESERVED_KEYS.includes(key)) {
return `${key}=${value}`; return `${key}=${value}`;
} }
return `${key}=`; return `${key}=`;
}); });
fs.writeFileSync(envExamplePath, processedLines.join("\n")); fs.writeFileSync(envExamplePath, processedLines.join("\n"));
console.log("File .env.example berhasil diperbarui!"); console.log("File .env.example berhasil diperbarui!");
} catch (error) { } catch (error) {
console.error("Error while creating .env.example:", error); console.error("Error while creating .env.example:", error);
process.exit(1); process.exit(1);
} }

View File

@ -1,51 +1,51 @@
/** /**
* Dynamically aggregates Elysia sub-routes from modular directories into a central registry. * Dynamically aggregates Elysia sub-routes from modular directories into a central registry.
* *
* @behavior * @behavior
* 1. Scans `./src/modules` for valid Elysia modules * 1. Scans `./src/modules` for valid Elysia modules
* 2. Generates imports and `.use()` calls for each module * 2. Generates imports and `.use()` calls for each module
* 3. Writes composed routes to `./src/routes.ts` * 3. Writes composed routes to `./src/routes.ts`
* *
* @requirements * @requirements
* - Module directories must contain an export named `[folderName]Module` * - Module directories must contain an export named `[folderName]Module`
* (e.g., `userModule` for `/user` folder) * (e.g., `userModule` for `/user` folder)
* - Modules must export an Elysia instance * - Modules must export an Elysia instance
* *
* @outputfile ./src/routes.ts * @outputfile ./src/routes.ts
* @examplegenerated * @examplegenerated
* ```ts * ```ts
* import Elysia from "elysia"; * import Elysia from "elysia";
* import { userModule } from './modules/user'; * import { userModule } from './modules/user';
* import { authModule } from './modules/auth'; * import { authModule } from './modules/auth';
* *
* const routes = new Elysia() * const routes = new Elysia()
* .use(userModule) * .use(userModule)
* .use(authModule); * .use(authModule);
* *
* export { routes }; * export { routes };
* ``` * ```
*/ */
import { writeFileSync, readdirSync } from "fs"; import { writeFileSync, readdirSync } from "fs";
import { join } from "path"; import { join } from "path";
const modulesPath = "./src/modules"; const modulesPath = "./src/modules";
const importLines: string[] = []; const importLines: string[] = [];
const useLines: string[] = []; const useLines: string[] = [];
for (const folder of readdirSync(modulesPath, { withFileTypes: true })) { for (const folder of readdirSync(modulesPath, { withFileTypes: true })) {
if (folder.isDirectory()) { if (folder.isDirectory()) {
const varName = `${folder.name}Module`; const varName = `${folder.name}Module`;
importLines.push(`import {${varName}} from './modules/${folder.name}';`); importLines.push(`import {${varName}} from './modules/${folder.name}';`);
useLines.push(`.use(${varName})`); useLines.push(`.use(${varName})`);
} }
} }
const content = ` const content = `
import Elysia from "elysia"; import Elysia from "elysia";
${importLines.join("\n")} ${importLines.join("\n")}
const routes = new Elysia() const routes = new Elysia()
${useLines.join("\n")}; ${useLines.join("\n")};
export { routes }; export { routes };
`; `;
writeFileSync(join(modulesPath, "../routes.ts"), content); writeFileSync(join(modulesPath, "../routes.ts"), content);

View File

@ -1,4 +1,4 @@
export const COOKIE_KEYS = { export const COOKIE_KEYS = {
AUTH: "auth_token", AUTH: "auth_token",
CSRF: "csrf_token", CSRF: "csrf_token",
}; };

View File

@ -1,80 +1,80 @@
/** /**
* Returns a standardized response for write operations (POST, PUT, DELETE). * Returns a standardized response for write operations (POST, PUT, DELETE).
* Only includes data in the response during development. * Only includes data in the response during development.
* *
* @param set - Function to set HTTP headers. * @param set - Function to set HTTP headers.
* @param status - HTTP status code of the response. * @param status - HTTP status code of the response.
* @param message - A message describing the result. * @param message - A message describing the result.
* @param data - Optional data for success responses or error description (only returned in development). * @param data - Optional data for success responses or error description (only returned in development).
* *
* @returns An object with `status`, `message`, and optionally `data` (in development only). * @returns An object with `status`, `message`, and optionally `data` (in development only).
*/ */
export function returnWriteResponse( export function returnWriteResponse(
set: any, set: any,
status: number, status: number,
message?: string, message?: string,
data?: any data?: any
) { ) {
set.status = status; set.status = status;
const response: Record<string, any> = { const response: Record<string, any> = {
status, status,
message, message,
}; };
if (process.env.APP_ENV === "development") response.data = data; if (process.env.APP_ENV === "development") response.data = data;
return response; return response;
} }
/** /**
* Returns a standardized response for read operations (GET). * Returns a standardized response for read operations (GET).
* Always includes data in the response regardless of the environment. * Always includes data in the response regardless of the environment.
* *
* @param set - Function to set HTTP headers. * @param set - Function to set HTTP headers.
* @param status - HTTP status code of the response. * @param status - HTTP status code of the response.
* @param message - A message describing the result. * @param message - A message describing the result.
* @param data - Data to include in the response. * @param data - Data to include in the response.
* *
* @returns An object with `status`, `message`, and `data`. * @returns An object with `status`, `message`, and `data`.
*/ */
export function returnReadResponse( export function returnReadResponse(
set: any, set: any,
status: number, status: number,
message: string, message: string,
data: any data: any
) { ) {
set.status = status; set.status = status;
return { return {
status, status,
message, message,
data, data,
}; };
} }
/** /**
* Returns a standardized error response for handling errors in catch blocks. * Returns a standardized error response for handling errors in catch blocks.
* *
* @param set - Function to set HTTP headers. * @param set - Function to set HTTP headers.
* @param status - HTTP status code of the error response. * @param status - HTTP status code of the error response.
* @param message - A message describing the error. * @param message - A message describing the error.
* @param errorDetails - Optional, detailed information about the error (e.g., stack trace). * @param errorDetails - Optional, detailed information about the error (e.g., stack trace).
* *
* @returns An object with `status`, `message`, and optionally `error_details` (in development only). * @returns An object with `status`, `message`, and optionally `error_details` (in development only).
*/ */
export function returnErrorResponse( export function returnErrorResponse(
set: any, set: any,
status: number, status: number,
message: string, message: string,
errorDetails?: any errorDetails?: any
) { ) {
set.status = status; set.status = status;
const response: Record<string, any> = { const response: Record<string, any> = {
status: "error", status: "error",
message, message,
}; };
if (process.env.APP_ENV === "development" && errorDetails) if (process.env.APP_ENV === "development" && errorDetails)
response.error_details = errorDetails; response.error_details = errorDetails;
return response; return response;
} }

View File

@ -1,54 +1,54 @@
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { returnErrorResponse } from "../../callback/httpResponse"; import { returnErrorResponse } from "../../callback/httpResponse";
import { AppError } from "../instances/app"; import { AppError } from "../instances/app";
import { PrismaErrorCodeList } from "../../../utils/databases/prisma/error/codeList"; import { PrismaErrorCodeList } from "../../../utils/databases/prisma/error/codeList";
export const mainErrorHandler = (set: any, error: unknown) => { export const mainErrorHandler = (set: any, error: unknown) => {
if (error instanceof AppError) { if (error instanceof AppError) {
return returnErrorResponse( return returnErrorResponse(
set, set,
error.statusCode, error.statusCode,
error.message, error.message,
error.details error.details
); );
} }
if (error instanceof Prisma.PrismaClientKnownRequestError) { if (error instanceof Prisma.PrismaClientKnownRequestError) {
const errorInfo = PrismaErrorCodeList[error.code]; const errorInfo = PrismaErrorCodeList[error.code];
if (errorInfo) if (errorInfo)
return returnErrorResponse( return returnErrorResponse(
set, set,
errorInfo.status, errorInfo.status,
errorInfo.message, errorInfo.message,
error.meta ?? {} error.meta ?? {}
); );
} }
if (error instanceof Prisma.PrismaClientUnknownRequestError) { if (error instanceof Prisma.PrismaClientUnknownRequestError) {
return returnErrorResponse(set, 500, "Unknown database error"); return returnErrorResponse(set, 500, "Unknown database error");
} }
if (error instanceof Prisma.PrismaClientRustPanicError) { if (error instanceof Prisma.PrismaClientRustPanicError) {
return returnErrorResponse( return returnErrorResponse(
set, set,
500, 500,
"Database engine crashed unexpectedly" "Database engine crashed unexpectedly"
); );
} }
if (error instanceof Prisma.PrismaClientInitializationError) { if (error instanceof Prisma.PrismaClientInitializationError) {
return returnErrorResponse(set, 503, `Can't reach database server.`, error); return returnErrorResponse(set, 503, `Can't reach database server.`, error);
} }
if (error instanceof Prisma.PrismaClientValidationError) { if (error instanceof Prisma.PrismaClientValidationError) {
return returnErrorResponse( return returnErrorResponse(
set, set,
400, 400,
"Invalid input to query", "Invalid input to query",
error.message error.message
); );
} }
return returnErrorResponse(set, 500, "Internal server error"); return returnErrorResponse(set, 500, "Internal server error");
}; };

View File

@ -1,13 +1,13 @@
export class AppError extends Error { export class AppError extends Error {
public readonly statusCode: number; public readonly statusCode: number;
public readonly details?: any; public readonly details?: any;
constructor(statusCode = 400, message: string, details?: any) { constructor(statusCode = 400, message: string, details?: any) {
super(message); super(message);
this.name = "AppError"; this.name = "AppError";
this.statusCode = statusCode; this.statusCode = statusCode;
this.details = details; this.details = details;
Object.setPrototypeOf(this, AppError.prototype); Object.setPrototypeOf(this, AppError.prototype);
} }
} }

View File

@ -1,21 +1,21 @@
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { AppError } from "./app"; import { AppError } from "./app";
export function ErrorForwarder( export function ErrorForwarder(
cause: unknown, cause: unknown,
statusCode: number = 500, statusCode: number = 500,
message: string = "Unexpected error" message: string = "Unexpected error"
): never { ): never {
if ( if (
cause instanceof AppError || cause instanceof AppError ||
cause instanceof Prisma.PrismaClientKnownRequestError || cause instanceof Prisma.PrismaClientKnownRequestError ||
cause instanceof Prisma.PrismaClientUnknownRequestError || cause instanceof Prisma.PrismaClientUnknownRequestError ||
cause instanceof Prisma.PrismaClientRustPanicError || cause instanceof Prisma.PrismaClientRustPanicError ||
cause instanceof Prisma.PrismaClientInitializationError || cause instanceof Prisma.PrismaClientInitializationError ||
cause instanceof Prisma.PrismaClientValidationError cause instanceof Prisma.PrismaClientValidationError
) { ) {
throw cause; throw cause;
} }
throw new AppError(statusCode, message, cause); throw new AppError(statusCode, message, cause);
} }

View File

@ -1,14 +1,14 @@
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
export const jwtDecode = (payload: string) => { export const jwtDecode = (payload: string) => {
// return payload; // return payload;
if (!payload) throw "JWT decode payload not found"; if (!payload) throw "JWT decode payload not found";
const JWTKey = process.env.JWT_SECRET!; const JWTKey = process.env.JWT_SECRET!;
try { try {
const decodedPayload = jwt.verify(payload, JWTKey); const decodedPayload = jwt.verify(payload, JWTKey);
return decodedPayload; return decodedPayload;
} catch (error) { } catch (error) {
throw "JWT expired or not valid"; throw "JWT expired or not valid";
} }
}; };

View File

@ -1,62 +1,62 @@
export interface JWTAuthToken { export interface JWTAuthToken {
id: string; id: string;
isAuthenticated: boolean; isAuthenticated: boolean;
userId: string; userId: string;
deviceType: string; deviceType: string;
deviceOs: string; deviceOs: string;
deviceIp: string; deviceIp: string;
isOnline: boolean; isOnline: boolean;
lastOnline: Date; lastOnline: Date;
validUntil: Date; validUntil: Date;
deletedAt: null; deletedAt: null;
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
user: User; user: User;
iat: number; iat: number;
exp: number; exp: number;
} }
interface User { interface User {
id: string; id: string;
name: string; name: string;
username: string; username: string;
email: string; email: string;
birthDate: null; birthDate: null;
gender: null; gender: null;
phoneCC: null; phoneCC: null;
phoneNumber: null; phoneNumber: null;
bioProfile: null; bioProfile: null;
profilePicture: null; profilePicture: null;
commentPicture: null; commentPicture: null;
preferenceId: null; preferenceId: null;
verifiedAt: null; verifiedAt: null;
disabledAt: null; disabledAt: null;
deletedAt: null; deletedAt: null;
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
roles: Role[]; roles: Role[];
} }
interface Role { interface Role {
id: string; id: string;
name: string; name: string;
primaryColor: string; primaryColor: string;
secondaryColor: string; secondaryColor: string;
pictureImage: string; pictureImage: string;
badgeImage: null; badgeImage: null;
isSuperadmin: boolean; isSuperadmin: boolean;
canEditMedia: boolean; canEditMedia: boolean;
canManageMedia: boolean; canManageMedia: boolean;
canEditEpisodes: boolean; canEditEpisodes: boolean;
canManageEpisodes: boolean; canManageEpisodes: boolean;
canEditComment: boolean; canEditComment: boolean;
canManageComment: boolean; canManageComment: boolean;
canEditUser: boolean; canEditUser: boolean;
canManageUser: boolean; canManageUser: boolean;
canEditSystem: boolean; canEditSystem: boolean;
canManageSystem: boolean; canManageSystem: boolean;
createdBy: string; createdBy: string;
deletedAt: null; deletedAt: null;
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
} }

View File

@ -1,11 +1,11 @@
import jwt from "jsonwebtoken"; import jwt from "jsonwebtoken";
export const jwtEncode = (payload: any) => { export const jwtEncode = (payload: any) => {
const tokenLifetime = Number(process.env.SESSION_EXPIRE!); const tokenLifetime = Number(process.env.SESSION_EXPIRE!);
const jwtSecret = process.env.JWT_SECRET!; const jwtSecret = process.env.JWT_SECRET!;
const jwtToken = jwt.sign(payload, jwtSecret, { const jwtToken = jwt.sign(payload, jwtSecret, {
expiresIn: tokenLifetime, expiresIn: tokenLifetime,
}); });
return jwtToken; return jwtToken;
}; };

View File

@ -1,33 +1,33 @@
import { serialize } from "cookie"; import { serialize } from "cookie";
export const clearCookies = ( export const clearCookies = (
set: any, set: any,
cookieKeys: string[], cookieKeys: string[],
options?: Partial<{ options?: Partial<{
httpOnly: boolean; httpOnly: boolean;
secure: boolean; secure: boolean;
sameSite: "strict" | "lax" | "none"; sameSite: "strict" | "lax" | "none";
path: string; path: string;
}> }>
) => { ) => {
// Define the default configurations for clearing cookies // Define the default configurations for clearing cookies
const defaultOptions = { const defaultOptions = {
httpOnly: true, httpOnly: true,
secure: true, secure: true,
sameSite: "strict" as const, sameSite: "strict" as const,
path: "/", path: "/",
...options, ...options,
}; };
// Create an array of cleared cookies with the specified names // Create an array of cleared cookies with the specified names
const clearedCookies = cookieKeys.map((name) => { const clearedCookies = cookieKeys.map((name) => {
return serialize(name, "", { return serialize(name, "", {
...defaultOptions, ...defaultOptions,
expires: new Date(0), expires: new Date(0),
}); });
}); });
// Set the cleared cookies in the response headers // Set the cleared cookies in the response headers
set.headers["set-cookie"] = clearedCookies; set.headers["set-cookie"] = clearedCookies;
return clearedCookies; return clearedCookies;
}; };

View File

@ -1,13 +1,13 @@
import { parse } from "cookie"; import { parse } from "cookie";
import { Context } from "elysia"; import { Context } from "elysia";
import { AppError } from "../../../error/instances/app"; import { AppError } from "../../../error/instances/app";
export const getCookie = (ctx: Context) => { export const getCookie = (ctx: Context) => {
try { try {
const cookiePayload = ctx.request.headers.get("Cookie"); const cookiePayload = ctx.request.headers.get("Cookie");
const cookies = parse(cookiePayload!); const cookies = parse(cookiePayload!);
return cookies; return cookies;
} catch (error) { } catch (error) {
throw new AppError(401, "Cookie not found"); throw new AppError(401, "Cookie not found");
} }
}; };

View File

@ -1,34 +1,34 @@
import { serialize } from "cookie"; import { serialize } from "cookie";
export const setCookie = async ( export const setCookie = async (
set: any, set: any,
name: string, name: string,
payload: string, payload: string,
options?: Partial<{ options?: Partial<{
httpOnly: boolean; httpOnly: boolean;
secure: boolean; secure: boolean;
sameSite: "strict" | "lax" | "none"; sameSite: "strict" | "lax" | "none";
maxAge: number; maxAge: number;
path: string; path: string;
}> }>
) => { ) => {
// Define the default configurations for the cookie // Define the default configurations for the cookie
const cookieLifetime = Number(process.env.SESSION_EXPIRE!); const cookieLifetime = Number(process.env.SESSION_EXPIRE!);
const defaultOptions = { const defaultOptions = {
httpOnly: true, httpOnly: true,
secure: true, secure: true,
sameSite: "strict" as const, sameSite: "strict" as const,
maxAge: cookieLifetime, maxAge: cookieLifetime,
path: "/", path: "/",
}; };
// Merge the default options with the provided options // Merge the default options with the provided options
const finalOptions = { ...defaultOptions, ...options }; const finalOptions = { ...defaultOptions, ...options };
// Create the serialized cookie string // Create the serialized cookie string
const serializedCookie = serialize(name, payload, finalOptions); const serializedCookie = serialize(name, payload, finalOptions);
// Set the cookie in the response headers // Set the cookie in the response headers
set.headers["set-cookie"] = serializedCookie; set.headers["set-cookie"] = serializedCookie;
return serializedCookie; return serializedCookie;
}; };

View File

@ -1,26 +1,26 @@
import { Context } from "elysia"; import { Context } from "elysia";
import { UAParser } from "ua-parser-js"; import { UAParser } from "ua-parser-js";
import { UserHeaderInformation } from "./types"; import { UserHeaderInformation } from "./types";
export const getUserHeaderInformation = ( export const getUserHeaderInformation = (
ctx: Context ctx: Context
): UserHeaderInformation => { ): UserHeaderInformation => {
const headers = ctx.request.headers; const headers = ctx.request.headers;
const userAgentHeader = headers.get("user-agent") || "desktop"; const userAgentHeader = headers.get("user-agent") || "desktop";
const userAgent = new UAParser(userAgentHeader); const userAgent = new UAParser(userAgentHeader);
const userIP = const userIP =
headers.get("cf-connecting-ip") || headers.get("cf-connecting-ip") ||
headers.get("x-real-ip") || headers.get("x-real-ip") ||
headers.get("x-forwarded-for")?.split(",")[0] || headers.get("x-forwarded-for")?.split(",")[0] ||
"Unknown IP"; "Unknown IP";
const userHeaderInformation = { const userHeaderInformation = {
ip: userIP, ip: userIP,
deviceType: userAgent.getDevice().type || "desktop", deviceType: userAgent.getDevice().type || "desktop",
deviceOS: userAgent.getOS().name + " " + userAgent.getOS().version, deviceOS: userAgent.getOS().name + " " + userAgent.getOS().version,
browser: userAgent.getBrowser().name + " " + userAgent.getBrowser().version, browser: userAgent.getBrowser().name + " " + userAgent.getBrowser().version,
}; };
return userHeaderInformation; return userHeaderInformation;
}; };

View File

@ -1,6 +1,6 @@
export interface UserHeaderInformation { export interface UserHeaderInformation {
ip: string; ip: string;
deviceType: string; deviceType: string;
deviceOS: string; deviceOS: string;
browser: string; browser: string;
} }

View File

@ -1,6 +1,6 @@
import bcrypt from "bcrypt"; import bcrypt from "bcrypt";
export const hashPassword = async (password: string): Promise<string> => { export const hashPassword = async (password: string): Promise<string> => {
const saltRounds = Number(process.env.SALT_ROUNDS); const saltRounds = Number(process.env.SALT_ROUNDS);
return await bcrypt.hash(password, saltRounds); return await bcrypt.hash(password, saltRounds);
}; };

View File

@ -1,8 +1,8 @@
import { Elysia } from "elysia"; import { Elysia } from "elysia";
import { routes } from "./routes"; import { routes } from "./routes";
const app = new Elysia().use(routes).listen(process.env.PORT || 3000); const app = new Elysia().use(routes).listen(process.env.PORT || 3000);
console.log( console.log(
`🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}` `🦊 Elysia is running at ${app.server?.hostname}:${app.server?.port}`
); );

View File

@ -1,14 +1,14 @@
import { Context } from "elysia"; import { Context } from "elysia";
import { getCookie } from "../helpers/http/userHeader/cookies/getCookies"; import { getCookie } from "../helpers/http/userHeader/cookies/getCookies";
import { mainErrorHandler } from "../helpers/error/handler"; import { mainErrorHandler } from "../helpers/error/handler";
import { returnErrorResponse } from "../helpers/callback/httpResponse"; import { returnErrorResponse } from "../helpers/callback/httpResponse";
export const authMiddleware = (ctx: Context) => { export const authMiddleware = (ctx: Context) => {
try { try {
const cookie = getCookie(ctx); const cookie = getCookie(ctx);
if (!cookie.auth_token) if (!cookie.auth_token)
return returnErrorResponse(ctx.set, 401, "User Unauthorized"); return returnErrorResponse(ctx.set, 401, "User Unauthorized");
} catch (error) { } catch (error) {
return mainErrorHandler(ctx.set, error); return mainErrorHandler(ctx.set, error);
} }
}; };

View File

@ -1,16 +1,16 @@
import { Context } from "elysia"; import { Context } from "elysia";
import { getCookie } from "../../helpers/http/userHeader/cookies/getCookies"; import { getCookie } from "../../helpers/http/userHeader/cookies/getCookies";
import { returnErrorResponse } from "../../helpers/callback/httpResponse"; import { returnErrorResponse } from "../../helpers/callback/httpResponse";
import { mainErrorHandler } from "../../helpers/error/handler"; import { mainErrorHandler } from "../../helpers/error/handler";
export const authMiddleware = (ctx: Context) => { export const authMiddleware = (ctx: Context) => {
try { try {
const cookie = getCookie(ctx); const cookie = getCookie(ctx);
if (!cookie.auth_token) if (!cookie.auth_token)
return returnErrorResponse(ctx.set, 401, "User Unauthorized"); return returnErrorResponse(ctx.set, 401, "User Unauthorized");
// pass // pass
} catch (error) { } catch (error) {
return mainErrorHandler(ctx.set, error); return mainErrorHandler(ctx.set, error);
} }
}; };

View File

@ -1,15 +1,15 @@
import { Context } from "elysia"; import { Context } from "elysia";
import { getCookie } from "../../helpers/http/userHeader/cookies/getCookies"; import { getCookie } from "../../helpers/http/userHeader/cookies/getCookies";
import { returnErrorResponse } from "../../helpers/callback/httpResponse"; import { returnErrorResponse } from "../../helpers/callback/httpResponse";
export const unautenticatedMiddleware = (ctx: Context) => { export const unautenticatedMiddleware = (ctx: Context) => {
try { try {
const cookies = getCookie(ctx); const cookies = getCookie(ctx);
if (cookies.auth_token) if (cookies.auth_token)
return returnErrorResponse(ctx.set, 403, "User already aunthenticated"); return returnErrorResponse(ctx.set, 403, "User already aunthenticated");
// pass // pass
} catch (error) { } catch (error) {
// pass // pass
} }
}; };

View File

@ -1,65 +1,65 @@
export interface LoginWithPasswordRequest { export interface LoginWithPasswordRequest {
identifier: string; identifier: string;
password: string; password: string;
} }
export interface JWTSessionPayload { export interface JWTSessionPayload {
id: string; id: string;
isAuthenticated: boolean; isAuthenticated: boolean;
userId: string; userId: string;
deviceType: string; deviceType: string;
deviceOs: string; deviceOs: string;
deviceIp: string; deviceIp: string;
isOnline: boolean; isOnline: boolean;
lastOnline: Date; lastOnline: Date;
validUntil: Date; validUntil: Date;
deletedAt: null; deletedAt: null;
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
user: User; user: User;
iat: number; iat: number;
exp: number; exp: number;
} }
interface User { interface User {
id: string; id: string;
name: string; name: string;
username: string; username: string;
email: string; email: string;
birthDate: null; birthDate: null;
gender: null; gender: null;
phoneCC: null; phoneCC: null;
phoneNumber: null; phoneNumber: null;
bioProfile: null; bioProfile: null;
profilePicture: null; profilePicture: null;
commentPicture: null; commentPicture: null;
preferenceId: null; preferenceId: null;
verifiedAt: null; verifiedAt: null;
disabledAt: null; disabledAt: null;
deletedAt: null; deletedAt: null;
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
roles: Role[]; roles: Role[];
} }
interface Role { interface Role {
id: string; id: string;
name: string; name: string;
primaryColor: string; primaryColor: string;
secondaryColor: string; secondaryColor: string;
pictureImage: string; pictureImage: string;
badgeImage: null; badgeImage: null;
isSuperadmin: boolean; isSuperadmin: boolean;
canEditMedia: boolean; canEditMedia: boolean;
canManageMedia: boolean; canManageMedia: boolean;
canEditEpisodes: boolean; canEditEpisodes: boolean;
canManageEpisodes: boolean; canManageEpisodes: boolean;
canEditComment: boolean; canEditComment: boolean;
canManageComment: boolean; canManageComment: boolean;
canEditUser: boolean; canEditUser: boolean;
canManageUser: boolean; canManageUser: boolean;
canEditSystem: boolean; canEditSystem: boolean;
canManageSystem: boolean; canManageSystem: boolean;
createdBy: string; createdBy: string;
deletedAt: null; deletedAt: null;
createdAt: Date; createdAt: Date;
updatedAt: Date; updatedAt: Date;
} }

View File

@ -1,27 +1,27 @@
import { import {
returnErrorResponse, returnErrorResponse,
returnWriteResponse, returnWriteResponse,
} from "../../../helpers/callback/httpResponse"; } from "../../../helpers/callback/httpResponse";
import { Context } from "elysia"; import { Context } from "elysia";
import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies"; import { getCookie } from "../../../helpers/http/userHeader/cookies/getCookies";
import { authVerificationService } from "../services/authVerification.service"; import { authVerificationService } from "../services/authVerification.service";
import { mainErrorHandler } from "../../../helpers/error/handler"; import { mainErrorHandler } from "../../../helpers/error/handler";
import { clearCookies } from "../../../helpers/http/userHeader/cookies/clearCookies"; import { clearCookies } from "../../../helpers/http/userHeader/cookies/clearCookies";
import { COOKIE_KEYS } from "../../../constants/cookie.keys"; import { COOKIE_KEYS } from "../../../constants/cookie.keys";
export const authVerification = async (ctx: Context) => { export const authVerification = async (ctx: Context) => {
try { try {
// Get the auth token from cookies // Get the auth token from cookies
const cookie = getCookie(ctx); const cookie = getCookie(ctx);
if (!cookie.auth_token) if (!cookie.auth_token)
return returnErrorResponse(ctx.set, 401, "Auth token not found"); return returnErrorResponse(ctx.set, 401, "Auth token not found");
// Verify the auth token and get the user session // Verify the auth token and get the user session
const authService = await authVerificationService(cookie.auth_token); const authService = await authVerificationService(cookie.auth_token);
return returnWriteResponse(ctx.set, 200, "User authenticated", authService); return returnWriteResponse(ctx.set, 200, "User authenticated", authService);
} catch (error) { } catch (error) {
// If token is invalid or expired, clear the auth cookie and return an error response // If token is invalid or expired, clear the auth cookie and return an error response
clearCookies(ctx.set, [COOKIE_KEYS.AUTH]); clearCookies(ctx.set, [COOKIE_KEYS.AUTH]);
return mainErrorHandler(ctx.set, error); return mainErrorHandler(ctx.set, error);
} }
}; };

View File

@ -1,41 +1,41 @@
import { import {
returnErrorResponse, returnErrorResponse,
returnWriteResponse, returnWriteResponse,
} from "../../../helpers/callback/httpResponse"; } from "../../../helpers/callback/httpResponse";
import { Context } from "elysia"; import { Context } from "elysia";
import { loginWithPasswordService } from "../services/loginWithPassword.service"; import { loginWithPasswordService } from "../services/loginWithPassword.service";
import { LoginWithPasswordRequest } from "../auth.types"; import { LoginWithPasswordRequest } from "../auth.types";
import { mainErrorHandler } from "../../../helpers/error/handler"; import { mainErrorHandler } from "../../../helpers/error/handler";
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation"; import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
import { setCookie } from "../../../helpers/http/userHeader/cookies/setCookies"; import { setCookie } from "../../../helpers/http/userHeader/cookies/setCookies";
import { COOKIE_KEYS } from "../../../constants/cookie.keys"; import { COOKIE_KEYS } from "../../../constants/cookie.keys";
import { loginWithPasswordSchema } from "../schemas/loginWithPassword"; import { loginWithPasswordSchema } from "../schemas/loginWithPassword";
export const loginWithPassword = async ( export const loginWithPassword = async (
ctx: Context & { body: LoginWithPasswordRequest } ctx: Context & { body: LoginWithPasswordRequest }
) => { ) => {
// Validate the request body against the schema // Validate the request body against the schema
const { error } = loginWithPasswordSchema.validate(ctx.body); const { error } = loginWithPasswordSchema.validate(ctx.body);
if (error || !ctx.body) if (error || !ctx.body)
return returnErrorResponse(ctx.set, 400, "Invalid user input", error); return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
// Extract user header information // Extract user header information
const userHeaderInfo = getUserHeaderInformation(ctx); const userHeaderInfo = getUserHeaderInformation(ctx);
try { try {
// Call the service to handle login with password // Call the service to handle login with password
const jwtToken = await loginWithPasswordService(ctx.body, userHeaderInfo); const jwtToken = await loginWithPasswordService(ctx.body, userHeaderInfo);
// Set the authentication cookie with the JWT token // Set the authentication cookie with the JWT token
setCookie(ctx.set, COOKIE_KEYS.AUTH, jwtToken); setCookie(ctx.set, COOKIE_KEYS.AUTH, jwtToken);
return returnWriteResponse( return returnWriteResponse(
ctx.set, ctx.set,
200, 200,
"Authentication Success", "Authentication Success",
jwtToken jwtToken
); );
} catch (error) { } catch (error) {
// Handle any errors that occur during the login process // Handle any errors that occur during the login process
return mainErrorHandler(ctx.set, error); return mainErrorHandler(ctx.set, error);
} }
}; };

View File

@ -1,10 +1,10 @@
import Elysia from "elysia"; import Elysia from "elysia";
import { loginWithPassword } from "./controller/loginWithPassword.controller"; import { loginWithPassword } from "./controller/loginWithPassword.controller";
import { authMiddleware } from "../../middleware/auth.middleware"; import { authMiddleware } from "../../middleware/auth.middleware";
import { authVerification } from "./controller/authVerification.controller"; import { authVerification } from "./controller/authVerification.controller";
export const authModule = new Elysia({ prefix: "/auth" }) export const authModule = new Elysia({ prefix: "/auth" })
.post("/legacy", loginWithPassword) .post("/legacy", loginWithPassword)
.post("/verification", authVerification, { .post("/verification", authVerification, {
beforeHandle: authMiddleware, beforeHandle: authMiddleware,
}); });

View File

@ -1,6 +1,6 @@
import Joi from "joi"; import Joi from "joi";
export const loginWithPasswordSchema = Joi.object({ export const loginWithPasswordSchema = Joi.object({
identifier: Joi.string().required(), identifier: Joi.string().required(),
password: Joi.string().required(), password: Joi.string().required(),
}); });

View File

@ -1,44 +1,44 @@
import { AppError } from "../../../helpers/error/instances/app"; import { AppError } from "../../../helpers/error/instances/app";
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder"; import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
import { jwtDecode } from "../../../helpers/http/jwt/decode"; import { jwtDecode } from "../../../helpers/http/jwt/decode";
import { checkUserSessionInCacheService } from "../../userSession/services/checkUserSessionInCache.service"; import { checkUserSessionInCacheService } from "../../userSession/services/checkUserSessionInCache.service";
import { getUserSessionFromDBService } from "../../userSession/services/getUserSessionFromDB.service"; import { getUserSessionFromDBService } from "../../userSession/services/getUserSessionFromDB.service";
import { storeUserSessionToCacheService } from "../../userSession/services/storeUserSessionToCache.service"; import { storeUserSessionToCacheService } from "../../userSession/services/storeUserSessionToCache.service";
import { JWTSessionPayload } from "../auth.types"; import { JWTSessionPayload } from "../auth.types";
export const authVerificationService = async (cookie: string) => { export const authVerificationService = async (cookie: string) => {
try { try {
// Decode the JWT token to get the session payload // Decode the JWT token to get the session payload
const jwtSession = jwtDecode(cookie) as JWTSessionPayload; const jwtSession = jwtDecode(cookie) as JWTSessionPayload;
// Check if the session exists in Redis // Check if the session exists in Redis
const sessionCheckOnRedis = await checkUserSessionInCacheService( const sessionCheckOnRedis = await checkUserSessionInCacheService(
jwtSession.userId, jwtSession.userId,
jwtSession.id jwtSession.id
); );
if (!sessionCheckOnRedis) { if (!sessionCheckOnRedis) {
// If not found in Redis, check the database // If not found in Redis, check the database
const sessionCheckOnDB = await getUserSessionFromDBService(jwtSession.id); const sessionCheckOnDB = await getUserSessionFromDBService(jwtSession.id);
// If the session found in the database, store it in Redis. if not, throw an error // If the session found in the database, store it in Redis. if not, throw an error
if (!sessionCheckOnDB) { if (!sessionCheckOnDB) {
throw new AppError(401, "Session invalid or expired"); throw new AppError(401, "Session invalid or expired");
} else { } else {
// Store the session in Redis with the remaining time until expiration // Store the session in Redis with the remaining time until expiration
const timeExpires = Math.floor( const timeExpires = Math.floor(
(new Date(sessionCheckOnDB.validUntil).getTime() - (new Date(sessionCheckOnDB.validUntil).getTime() -
new Date().getTime()) / new Date().getTime()) /
1000 1000
); );
await storeUserSessionToCacheService(sessionCheckOnDB, timeExpires); await storeUserSessionToCacheService(sessionCheckOnDB, timeExpires);
return sessionCheckOnDB; return sessionCheckOnDB;
} }
} else { } else {
// If the session is found in Redis, return it // If the session is found in Redis, return it
return jwtSession; return jwtSession;
} }
} catch (error) { } catch (error) {
ErrorForwarder(error, 401, "Token is invalid"); ErrorForwarder(error, 401, "Token is invalid");
} }
}; };

View File

@ -1,37 +1,37 @@
import bcrypt from "bcrypt"; import bcrypt from "bcrypt";
import { findUserByEmailOrUsernameService } from "../../user/services/findUserByEmailOrUsername.service"; import { findUserByEmailOrUsernameService } from "../../user/services/findUserByEmailOrUsername.service";
import { LoginWithPasswordRequest } from "../auth.types"; import { LoginWithPasswordRequest } from "../auth.types";
import { AppError } from "../../../helpers/error/instances/app"; import { AppError } from "../../../helpers/error/instances/app";
import { UserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation/types"; import { UserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation/types";
import { createUserSessionService } from "../../userSession/services/createUserSession.service"; import { createUserSessionService } from "../../userSession/services/createUserSession.service";
import { jwtEncode } from "../../../helpers/http/jwt/encode"; import { jwtEncode } from "../../../helpers/http/jwt/encode";
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder"; import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
export const loginWithPasswordService = async ( export const loginWithPasswordService = async (
request: LoginWithPasswordRequest, request: LoginWithPasswordRequest,
userHeaderInfo: UserHeaderInformation userHeaderInfo: UserHeaderInformation
) => { ) => {
try { try {
// search for user data using an identifier (username or email) // search for user data using an identifier (username or email)
const userData = await findUserByEmailOrUsernameService(request.identifier); const userData = await findUserByEmailOrUsernameService(request.identifier);
// if user data is not found, throw an error // if user data is not found, throw an error
if (!userData) throw new AppError(404, "User not found"); if (!userData) throw new AppError(404, "User not found");
// validate the password in the request with the existing one // validate the password in the request with the existing one
if (!(await bcrypt.compare(request.password, userData.password))) if (!(await bcrypt.compare(request.password, userData.password)))
throw new AppError(401, "Password incorrect"); throw new AppError(401, "Password incorrect");
// create new user session // create new user session
const userSession = await createUserSessionService({ const userSession = await createUserSessionService({
userId: userData.id, userId: userData.id,
userHeaderInformation: userHeaderInfo, userHeaderInformation: userHeaderInfo,
}); });
// create JWT token that contain user session // create JWT token that contain user session
const jwtToken = jwtEncode(userSession); const jwtToken = jwtEncode(userSession);
return jwtToken; return jwtToken;
} catch (error) { } catch (error) {
ErrorForwarder(error); ErrorForwarder(error);
} }
}; };

View File

@ -1,15 +1,15 @@
import { Context } from "elysia"; import { Context } from "elysia";
import { mainErrorHandler } from "../../helpers/error/handler"; import { mainErrorHandler } from "../../helpers/error/handler";
import { debugService } from "./debug.service"; import { debugService } from "./debug.service";
import { returnWriteResponse } from "../../helpers/callback/httpResponse"; import { returnWriteResponse } from "../../helpers/callback/httpResponse";
export const debugController = async (ctx: Context) => { export const debugController = async (ctx: Context) => {
try { try {
const dataFromService = await debugService(); const dataFromService = await debugService();
return returnWriteResponse(ctx.set, 200, "Message Sent", dataFromService); return returnWriteResponse(ctx.set, 200, "Message Sent", dataFromService);
} catch (error) { } catch (error) {
return mainErrorHandler(ctx.set, error); return mainErrorHandler(ctx.set, error);
} }
}; };
// buat debug untuk date to number (second) // buat debug untuk date to number (second)

View File

@ -1,11 +1,11 @@
import { ErrorForwarder } from "../../helpers/error/instances/forwarder"; import { ErrorForwarder } from "../../helpers/error/instances/forwarder";
import { debug2Service } from "./debug2.service"; import { debug2Service } from "./debug2.service";
export const debugService = async () => { export const debugService = async () => {
try { try {
const dataFromService = await debug2Service(); const dataFromService = await debug2Service();
return dataFromService; return dataFromService;
} catch (error) { } catch (error) {
ErrorForwarder(error); ErrorForwarder(error);
} }
}; };

View File

@ -1,11 +1,11 @@
import { ErrorForwarder } from "../../helpers/error/instances/forwarder"; import { ErrorForwarder } from "../../helpers/error/instances/forwarder";
import { debug3Service } from "./debug3.service"; import { debug3Service } from "./debug3.service";
export const debug2Service = async () => { export const debug2Service = async () => {
try { try {
const dataFromService = await debug3Service(); const dataFromService = await debug3Service();
return dataFromService; return dataFromService;
} catch (error) { } catch (error) {
ErrorForwarder(error, 502); ErrorForwarder(error, 502);
} }
}; };

View File

@ -1,9 +1,9 @@
import { AppError } from "../../helpers/error/instances/app"; import { AppError } from "../../helpers/error/instances/app";
import { ErrorForwarder } from "../../helpers/error/instances/forwarder"; import { ErrorForwarder } from "../../helpers/error/instances/forwarder";
export const debug3Service = async () => { export const debug3Service = async () => {
// throw new AppError(402, "Error from 3"); // throw new AppError(402, "Error from 3");
const data = "RAWR"; const data = "RAWR";
// return data; // return data;
ErrorForwarder(data); ErrorForwarder(data);
}; };

View File

@ -1,7 +1,7 @@
import Elysia from "elysia"; import Elysia from "elysia";
import { debugController } from "./debug.controller"; import { debugController } from "./debug.controller";
export const debugModule = new Elysia({ prefix: "/debug" }).get( export const debugModule = new Elysia({ prefix: "/debug" }).get(
"/", "/",
debugController debugController
); );

View File

@ -1,50 +1,50 @@
import { import {
returnErrorResponse, returnErrorResponse,
returnWriteResponse, returnWriteResponse,
} from "../../../helpers/callback/httpResponse"; } from "../../../helpers/callback/httpResponse";
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { Context } from "elysia"; import { Context } from "elysia";
import { createUserService } from "../services/createUser.service"; import { createUserService } from "../services/createUser.service";
import { mainErrorHandler } from "../../../helpers/error/handler"; import { mainErrorHandler } from "../../../helpers/error/handler";
import { createUserSchema } from "../schemas/createUser.schema"; import { createUserSchema } from "../schemas/createUser.schema";
/** /**
* @function createUser * @function createUser
* @description Creates a new user in the database. * @description Creates a new user in the database.
* *
* @param {Context & { body: Prisma.UserCreateInput }} ctx - The context object containing the request body. * @param {Context & { body: Prisma.UserCreateInput }} ctx - The context object containing the request body.
* @param {Prisma.UserCreateInput} ctx.body - The user data to be created. * @param {Prisma.UserCreateInput} ctx.body - The user data to be created.
* *
* @returns {Promise<Object>} A response object indicating success or failure. * @returns {Promise<Object>} A response object indicating success or failure.
* @throws {Object} An error response object if validation fails or an error occurs during user creation. * @throws {Object} An error response object if validation fails or an error occurs during user creation.
* *
* @example * @example
* Request route: POST /users * Request route: POST /users
* Request body: * Request body:
* { * {
* "username": "john_doe", * "username": "john_doe",
* "email": "john@example.com", * "email": "john@example.com",
* "password": "password123" * "password": "password123"
* } * }
*/ */
export const createUser = async ( export const createUser = async (
ctx: Context & { body: Prisma.UserCreateInput } ctx: Context & { body: Prisma.UserCreateInput }
) => { ) => {
// Validate the user input using a validation schema // Validate the user input using a validation schema
const { error } = createUserSchema.validate(ctx.body); const { error } = createUserSchema.validate(ctx.body);
if (error) if (error)
return returnErrorResponse(ctx.set, 400, "Invalid user input", error); return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
// Create the user in the database using the service // Create the user in the database using the service
try { try {
const newUser = await createUserService(ctx.body); const newUser = await createUserService(ctx.body);
return returnWriteResponse( return returnWriteResponse(
ctx.set, ctx.set,
201, 201,
"User created successfully", "User created successfully",
newUser newUser
); );
} catch (error) { } catch (error) {
return mainErrorHandler(ctx.set, error); return mainErrorHandler(ctx.set, error);
} }
}; };

View File

@ -1,21 +1,21 @@
import { import {
returnErrorResponse, returnErrorResponse,
returnReadResponse, returnReadResponse,
} from "../../../helpers/callback/httpResponse"; } from "../../../helpers/callback/httpResponse";
import { Context } from "elysia"; import { Context } from "elysia";
import { getAllUsersService } from "../services/getAllUser.service"; import { getAllUsersService } from "../services/getAllUser.service";
import { mainErrorHandler } from "../../../helpers/error/handler"; import { mainErrorHandler } from "../../../helpers/error/handler";
export const getAllUser = async (ctx: Context) => { export const getAllUser = async (ctx: Context) => {
try { try {
const allUser = await getAllUsersService(); const allUser = await getAllUsersService();
return returnReadResponse( return returnReadResponse(
ctx.set, ctx.set,
200, 200,
"All user ranks successfully", "All user ranks successfully",
allUser allUser
); );
} catch (error) { } catch (error) {
return mainErrorHandler(ctx.set, error); return mainErrorHandler(ctx.set, error);
} }
}; };

View File

@ -1,7 +1,7 @@
import Elysia from "elysia"; import Elysia from "elysia";
import { getAllUser } from "./controller/getAllUser.controller"; import { getAllUser } from "./controller/getAllUser.controller";
import { createUser } from "./controller/createUser.controller"; import { createUser } from "./controller/createUser.controller";
export const userModule = new Elysia({ prefix: "/users" }) export const userModule = new Elysia({ prefix: "/users" })
.get("/", getAllUser) .get("/", getAllUser)
.post("/", createUser); .post("/", createUser);

View File

@ -1,17 +1,17 @@
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { userModel } from "../user.model"; import { userModel } from "../user.model";
export const createUserRepo = async (data: Prisma.UserCreateInput) => { export const createUserRepo = async (data: Prisma.UserCreateInput) => {
try { try {
const userData = await userModel.create({ const userData = await userModel.create({
data, data,
omit: { omit: {
password: true, password: true,
}, },
}); });
return userData; return userData;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };

View File

@ -1,39 +1,39 @@
import { AppError } from "../../../helpers/error/instances/app"; import { AppError } from "../../../helpers/error/instances/app";
import { userModel } from "../user.model"; import { userModel } from "../user.model";
export const findUserByEmailOrUsernameRepo = async (identifier: string) => { export const findUserByEmailOrUsernameRepo = async (identifier: string) => {
try { try {
const userData = const userData =
(await userModel.findUnique({ (await userModel.findUnique({
where: { email: identifier }, where: { email: identifier },
include: { include: {
roles: { roles: {
omit: { omit: {
createdBy: true, createdBy: true,
createdAt: true, createdAt: true,
updatedAt: true, updatedAt: true,
deletedAt: true, deletedAt: true,
}, },
}, },
}, },
})) || })) ||
(await userModel.findUnique({ (await userModel.findUnique({
where: { username: identifier }, where: { username: identifier },
include: { include: {
roles: { roles: {
omit: { omit: {
createdBy: true, createdBy: true,
createdAt: true, createdAt: true,
updatedAt: true, updatedAt: true,
deletedAt: true, deletedAt: true,
}, },
}, },
}, },
})); }));
if (!userData) return false; if (!userData) return false;
return userData; return userData;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };

View File

@ -1,15 +1,15 @@
import { userModel } from "../user.model"; import { userModel } from "../user.model";
export const getAllUserRepo = async () => { export const getAllUserRepo = async () => {
try { try {
const data = await userModel.findMany({ const data = await userModel.findMany({
where: { where: {
deletedAt: null, deletedAt: null,
}, },
}); });
return data; return data;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };

View File

@ -1,15 +1,15 @@
import Joi from "joi"; import Joi from "joi";
export const createUserSchema = Joi.object({ export const createUserSchema = Joi.object({
name: Joi.string().min(4).max(255).required(), name: Joi.string().min(4).max(255).required(),
username: Joi.string().min(4).max(255).required(), username: Joi.string().min(4).max(255).required(),
email: Joi.string().email().required(), email: Joi.string().email().required(),
password: Joi.string().min(8).max(255).required(), password: Joi.string().min(8).max(255).required(),
birthdate: Joi.date(), birthdate: Joi.date(),
gender: Joi.string().valid("male", "female"), gender: Joi.string().valid("male", "female"),
phoneCC: Joi.string().min(2).max(2), phoneCC: Joi.string().min(2).max(2),
phoneNumber: Joi.string().min(7).max(15), phoneNumber: Joi.string().min(7).max(15),
bioProfile: Joi.string().max(300), bioProfile: Joi.string().max(300),
profilePicture: Joi.string().uri(), profilePicture: Joi.string().uri(),
commentPicture: Joi.string().uri(), commentPicture: Joi.string().uri(),
}); });

View File

@ -1,18 +1,18 @@
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { hashPassword } from "../../../helpers/security/password/hash"; import { hashPassword } from "../../../helpers/security/password/hash";
import { createUserRepo } from "../repositories/createUser.repository"; import { createUserRepo } from "../repositories/createUser.repository";
export const createUserService = async (userData: Prisma.UserCreateInput) => { export const createUserService = async (userData: Prisma.UserCreateInput) => {
const { password, ...rest } = userData; // Destructure the password and the rest of the user data const { password, ...rest } = userData; // Destructure the password and the rest of the user data
const hashedPassword = await hashPassword(password); // Hash the password before saving to the database const hashedPassword = await hashPassword(password); // Hash the password before saving to the database
try { try {
const newUser = await createUserRepo({ const newUser = await createUserRepo({
...rest, ...rest,
password: hashedPassword, password: hashedPassword,
}); });
return newUser; return newUser;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };

View File

@ -1,11 +1,11 @@
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder"; import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
import { findUserByEmailOrUsernameRepo } from "../repositories/findUserByEmailOrUsername.repository"; import { findUserByEmailOrUsernameRepo } from "../repositories/findUserByEmailOrUsername.repository";
export const findUserByEmailOrUsernameService = async (identifier: string) => { export const findUserByEmailOrUsernameService = async (identifier: string) => {
try { try {
const userData = await findUserByEmailOrUsernameRepo(identifier); const userData = await findUserByEmailOrUsernameRepo(identifier);
return userData; return userData;
} catch (error) { } catch (error) {
ErrorForwarder(error); ErrorForwarder(error);
} }
}; };

View File

@ -1,10 +1,10 @@
import { getAllUserRepo } from "../repositories/getAllUser.repository"; import { getAllUserRepo } from "../repositories/getAllUser.repository";
export const getAllUsersService = async () => { export const getAllUsersService = async () => {
try { try {
const allUser = await getAllUserRepo(); const allUser = await getAllUserRepo();
return allUser; return allUser;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };

View File

@ -1,3 +1,3 @@
import { prisma } from "../../utils/databases/prisma/connection"; import { prisma } from "../../utils/databases/prisma/connection";
export const userModel = prisma.user; export const userModel = prisma.user;

View File

@ -1,67 +1,67 @@
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { Context } from "elysia"; import { Context } from "elysia";
import { import {
returnErrorResponse, returnErrorResponse,
returnWriteResponse, returnWriteResponse,
} from "../../../helpers/callback/httpResponse"; } from "../../../helpers/callback/httpResponse";
import { createUserRoleService } from "../services/createUserRole.service"; import { createUserRoleService } from "../services/createUserRole.service";
import { mainErrorHandler } from "../../../helpers/error/handler"; import { mainErrorHandler } from "../../../helpers/error/handler";
import { createUserRoleSchema } from "../schemas/createUserRole.schema"; import { createUserRoleSchema } from "../schemas/createUserRole.schema";
/** /**
* @function createUserRole * @function createUserRole
* @description Creates a new user role in the database. * @description Creates a new user role in the database.
* *
* @param {Context & { body: UserRole }} ctx - The context object containing the request body. * @param {Context & { body: UserRole }} ctx - The context object containing the request body.
* @param {UserRole} ctx.body - The user role data to be created. * @param {UserRole} ctx.body - The user role data to be created.
* *
* @returns {Promise<Object>} A response object indicating success or failure. * @returns {Promise<Object>} A response object indicating success or failure.
* @throws {Object} An error response object if validation fails or an error occurs during role creation. * @throws {Object} An error response object if validation fails or an error occurs during role creation.
* *
* @example * @example
* Request route: POST /roles * Request route: POST /roles
* Request body: * Request body:
* { * {
* "userID": "e31668e6-c261-4a7e-9469-ffad734cf2dd", * "userID": "e31668e6-c261-4a7e-9469-ffad734cf2dd",
* "name": "Admin", * "name": "Admin",
* "primaryColor": "#D9D9D9", * "primaryColor": "#D9D9D9",
* "secondaryColor": "#FFFFFF", * "secondaryColor": "#FFFFFF",
* "pictureImage": "https://example.com/picture.jpg", * "pictureImage": "https://example.com/picture.jpg",
* "badgeImage": "https://example.com/badge.jpg", * "badgeImage": "https://example.com/badge.jpg",
* "isSuperadmin": false, * "isSuperadmin": false,
* "canEditMedia": false, * "canEditMedia": false,
* "canManageMedia": false, * "canManageMedia": false,
* "canEditEpisodes": false, * "canEditEpisodes": false,
* "canManageEpisodes": false, * "canManageEpisodes": false,
* "canEditComment": false, * "canEditComment": false,
* "canManageComment": false, * "canManageComment": false,
* "canEditUser": false, * "canEditUser": false,
* "canManageUser": false, * "canManageUser": false,
* "canEditSystem": false, * "canEditSystem": false,
* "canManageSystem": false * "canManageSystem": false
* } * }
*/ */
export const createUserRole = async ( export const createUserRole = async (
ctx: Context & { body: Prisma.UserRoleUncheckedCreateInput } ctx: Context & { body: Prisma.UserRoleUncheckedCreateInput }
) => { ) => {
const { error } = createUserRoleSchema.validate(ctx.body); const { error } = createUserRoleSchema.validate(ctx.body);
if (error) if (error)
return returnErrorResponse(ctx.set, 400, "Invalid user input", error); return returnErrorResponse(ctx.set, 400, "Invalid user input", error);
const formData: Prisma.UserRoleUncheckedCreateInput = { const formData: Prisma.UserRoleUncheckedCreateInput = {
...ctx.body, ...ctx.body,
createdBy: "daw", createdBy: "daw",
}; };
try { try {
const newUserRole = await createUserRoleService(formData); const newUserRole = await createUserRoleService(formData);
return returnWriteResponse( return returnWriteResponse(
ctx.set, ctx.set,
201, 201,
"User role created successfully", "User role created successfully",
newUserRole newUserRole
); );
} catch (error) { } catch (error) {
return mainErrorHandler(ctx.set, error); return mainErrorHandler(ctx.set, error);
} }
}; };

View File

@ -1,9 +1,9 @@
import Elysia from "elysia"; import Elysia from "elysia";
import { createUserRole } from "./controller/createUserRole.controller"; import { createUserRole } from "./controller/createUserRole.controller";
import { unautenticatedMiddleware } from "../../middleware/auth/unauthenticated.middleware"; import { unautenticatedMiddleware } from "../../middleware/auth/unauthenticated.middleware";
export const userRoleModule = new Elysia({ prefix: "/roles" }) export const userRoleModule = new Elysia({ prefix: "/roles" })
.get("/", () => "Hello User Role Module", { .get("/", () => "Hello User Role Module", {
beforeHandle: unautenticatedMiddleware, beforeHandle: unautenticatedMiddleware,
}) })
.post("/", createUserRole); .post("/", createUserRole);

View File

@ -1,15 +1,15 @@
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { userRoleModel } from "../userRole.model"; import { userRoleModel } from "../userRole.model";
export const createUserRoleRepo = async ( export const createUserRoleRepo = async (
data: Prisma.UserRoleUncheckedCreateInput data: Prisma.UserRoleUncheckedCreateInput
) => { ) => {
try { try {
const newUserRole = await userRoleModel.create({ const newUserRole = await userRoleModel.create({
data, data,
}); });
return newUserRole; return newUserRole;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };

View File

@ -1,28 +1,28 @@
import Joi from "joi"; import Joi from "joi";
export const createUserRoleSchema = Joi.object({ export const createUserRoleSchema = Joi.object({
name: Joi.string().min(4).max(255).required(), name: Joi.string().min(4).max(255).required(),
primaryColor: Joi.string() primaryColor: Joi.string()
.pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/) .pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)
.optional(), .optional(),
secondaryColor: Joi.string() secondaryColor: Joi.string()
.pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/) .pattern(/^#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})$/)
.optional(), .optional(),
pictureImage: Joi.string() pictureImage: Joi.string()
.uri({ scheme: ["http", "https"] }) .uri({ scheme: ["http", "https"] })
.optional(), .optional(),
badgeImage: Joi.string() badgeImage: Joi.string()
.uri({ scheme: ["http", "https"] }) .uri({ scheme: ["http", "https"] })
.optional(), .optional(),
isSuperadmin: Joi.boolean().required(), isSuperadmin: Joi.boolean().required(),
canEditMedia: Joi.boolean().required(), canEditMedia: Joi.boolean().required(),
canManageMedia: Joi.boolean().required(), canManageMedia: Joi.boolean().required(),
canEditEpisodes: Joi.boolean().required(), canEditEpisodes: Joi.boolean().required(),
canManageEpisodes: Joi.boolean().required(), canManageEpisodes: Joi.boolean().required(),
canEditComment: Joi.boolean().required(), canEditComment: Joi.boolean().required(),
canManageComment: Joi.boolean().required(), canManageComment: Joi.boolean().required(),
canEditUser: Joi.boolean().required(), canEditUser: Joi.boolean().required(),
canManageUser: Joi.boolean().required(), canManageUser: Joi.boolean().required(),
canEditSystem: Joi.boolean().required(), canEditSystem: Joi.boolean().required(),
canManageSystem: Joi.boolean().required(), canManageSystem: Joi.boolean().required(),
}); });

View File

@ -1,28 +1,28 @@
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { createUserRoleRepo } from "../repositories/createUserRole.repository"; import { createUserRoleRepo } from "../repositories/createUserRole.repository";
export const createUserRoleService = async ( export const createUserRoleService = async (
userRoleData: Prisma.UserRoleUncheckedCreateInput userRoleData: Prisma.UserRoleUncheckedCreateInput
) => { ) => {
try { try {
const dataPayload = { const dataPayload = {
...userRoleData, ...userRoleData,
isSuperadmin: Boolean(userRoleData.isSuperadmin), isSuperadmin: Boolean(userRoleData.isSuperadmin),
canEditMedia: Boolean(userRoleData.canEditMedia), canEditMedia: Boolean(userRoleData.canEditMedia),
canManageMedia: Boolean(userRoleData.canManageMedia), canManageMedia: Boolean(userRoleData.canManageMedia),
canEditEpisodes: Boolean(userRoleData.canEditEpisodes), canEditEpisodes: Boolean(userRoleData.canEditEpisodes),
canManageEpisodes: Boolean(userRoleData.canManageEpisodes), canManageEpisodes: Boolean(userRoleData.canManageEpisodes),
canEditComment: Boolean(userRoleData.canEditComment), canEditComment: Boolean(userRoleData.canEditComment),
canManageComment: Boolean(userRoleData.canManageComment), canManageComment: Boolean(userRoleData.canManageComment),
canEditUser: Boolean(userRoleData.canEditUser), canEditUser: Boolean(userRoleData.canEditUser),
canManageUser: Boolean(userRoleData.canManageUser), canManageUser: Boolean(userRoleData.canManageUser),
canEditSystem: Boolean(userRoleData.canEditSystem), canEditSystem: Boolean(userRoleData.canEditSystem),
canManageSystem: Boolean(userRoleData.canManageSystem), canManageSystem: Boolean(userRoleData.canManageSystem),
deletedAt: null, deletedAt: null,
}; };
const newUserRole = await createUserRoleRepo(dataPayload); const newUserRole = await createUserRoleRepo(dataPayload);
return newUserRole; return newUserRole;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };

View File

@ -1,3 +1,3 @@
import { prisma } from "../../utils/databases/prisma/connection"; import { prisma } from "../../utils/databases/prisma/connection";
export const userRoleModel = prisma.userRole; export const userRoleModel = prisma.userRole;

View File

@ -1,35 +1,35 @@
import { Context } from "elysia"; import { Context } from "elysia";
import { createUserSessionService } from "../services/createUserSession.service"; import { createUserSessionService } from "../services/createUserSession.service";
import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation"; import { getUserHeaderInformation } from "../../../helpers/http/userHeader/getUserHeaderInformation";
import { mainErrorHandler } from "../../../helpers/error/handler"; import { mainErrorHandler } from "../../../helpers/error/handler";
import { import {
returnErrorResponse, returnErrorResponse,
returnWriteResponse, returnWriteResponse,
} from "../../../helpers/callback/httpResponse"; } from "../../../helpers/callback/httpResponse";
export const createUserSessionRole = async ( export const createUserSessionRole = async (
ctx: Context & { body: { userId?: string } } ctx: Context & { body: { userId?: string } }
) => { ) => {
// Validate request body // Validate request body
if (!ctx.body?.userId) { if (!ctx.body?.userId) {
return returnErrorResponse(ctx.set, 400, "User ID is required"); return returnErrorResponse(ctx.set, 400, "User ID is required");
} }
// Get user device and browser information // Get user device and browser information
const userHeaderData = getUserHeaderInformation(ctx); const userHeaderData = getUserHeaderInformation(ctx);
try { try {
const newUserSession = await createUserSessionService({ const newUserSession = await createUserSessionService({
userId: ctx.body.userId, userId: ctx.body.userId,
userHeaderInformation: userHeaderData, userHeaderInformation: userHeaderData,
}); });
return returnWriteResponse( return returnWriteResponse(
ctx.set, ctx.set,
201, 201,
"User session created", "User session created",
newUserSession newUserSession
); );
} catch (error) { } catch (error) {
return mainErrorHandler(ctx.set, error); return mainErrorHandler(ctx.set, error);
} }
}; };

View File

@ -1,7 +1,7 @@
import Elysia from "elysia"; import Elysia from "elysia";
import { createUserSessionRole } from "./controllers/createUserSession.controller"; import { createUserSessionRole } from "./controllers/createUserSession.controller";
export const userSessionModule = new Elysia({ prefix: "/user-sessions" }).post( export const userSessionModule = new Elysia({ prefix: "/user-sessions" }).post(
"/", "/",
createUserSessionRole createUserSessionRole
); );

View File

@ -1,13 +1,13 @@
import { AppError } from "../../../helpers/error/instances/app"; import { AppError } from "../../../helpers/error/instances/app";
import { redis } from "../../../utils/databases/redis/connection"; import { redis } from "../../../utils/databases/redis/connection";
export const checkUserSessionInCacheRepo = async (redisKeyName: string) => { export const checkUserSessionInCacheRepo = async (redisKeyName: string) => {
try { try {
const userSessionInRedis = await redis.exists(redisKeyName); const userSessionInRedis = await redis.exists(redisKeyName);
if (!userSessionInRedis) return false; if (!userSessionInRedis) return false;
return userSessionInRedis; return userSessionInRedis;
} catch (error) { } catch (error) {
throw new AppError(500, "Server cache error", error); throw new AppError(500, "Server cache error", error);
} }
}; };

View File

@ -1,33 +1,33 @@
import { AppError } from "../../../helpers/error/instances/app"; import { AppError } from "../../../helpers/error/instances/app";
import { prisma } from "../../../utils/databases/prisma/connection"; import { prisma } from "../../../utils/databases/prisma/connection";
export const findUniqueUserSessionInDBRepo = async (identifier: string) => { export const findUniqueUserSessionInDBRepo = async (identifier: string) => {
try { try {
const userSession = await prisma.userSession.findUnique({ const userSession = await prisma.userSession.findUnique({
where: { where: {
id: identifier, id: identifier,
}, },
include: { include: {
user: { user: {
omit: { omit: {
password: true, password: true,
updatedAt: true, updatedAt: true,
}, },
include: { include: {
roles: true, roles: true,
}, },
}, },
}, },
omit: { omit: {
deletedAt: true, deletedAt: true,
updatedAt: true, updatedAt: true,
}, },
}); });
if (!userSession) return false; if (!userSession) return false;
return userSession; return userSession;
} catch (error) { } catch (error) {
throw new AppError(500, "Database Error", error); throw new AppError(500, "Database Error", error);
} }
}; };

View File

@ -1,32 +1,32 @@
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { userSessionModel } from "../userSession.model"; import { userSessionModel } from "../userSession.model";
import { AppError } from "../../../helpers/error/instances/app"; import { AppError } from "../../../helpers/error/instances/app";
export const createUserSessionRepo = async ( export const createUserSessionRepo = async (
data: Prisma.UserSessionUncheckedCreateInput data: Prisma.UserSessionUncheckedCreateInput
) => { ) => {
try { try {
const newUserSession = await userSessionModel.create({ const newUserSession = await userSessionModel.create({
data: data, data: data,
include: { include: {
user: { user: {
omit: { omit: {
password: true, password: true,
}, },
include: { include: {
roles: true, roles: true,
}, },
}, },
}, },
omit: { omit: {
lastOnline: true, lastOnline: true,
deletedAt: true, deletedAt: true,
createdAt: true, createdAt: true,
updatedAt: true, updatedAt: true,
}, },
}); });
return newUserSession; return newUserSession;
} catch (error) { } catch (error) {
throw error; throw error;
} }
}; };

View File

@ -1,19 +1,19 @@
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { AppError } from "../../../helpers/error/instances/app"; import { AppError } from "../../../helpers/error/instances/app";
import { redis } from "../../../utils/databases/redis/connection"; import { redis } from "../../../utils/databases/redis/connection";
export const storeUserSessionToCacheRepo = async ( export const storeUserSessionToCacheRepo = async (
userSession: Prisma.UserSessionUncheckedCreateInput, userSession: Prisma.UserSessionUncheckedCreateInput,
timeExpires: number timeExpires: number
) => { ) => {
try { try {
await redis.set( await redis.set(
`${process.env.app_name}:users:${userSession.userId}:sessions:${userSession.id}`, `${process.env.app_name}:users:${userSession.userId}:sessions:${userSession.id}`,
String(userSession.validUntil), String(userSession.validUntil),
"EX", "EX",
timeExpires timeExpires
); );
} catch (error) { } catch (error) {
throw new AppError(401, "Failed to store user session to cache"); throw new AppError(401, "Failed to store user session to cache");
} }
}; };

View File

@ -1,19 +1,19 @@
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder"; import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
import { checkUserSessionInCacheRepo } from "../repositories/checkUserSessionInCache.repository"; import { checkUserSessionInCacheRepo } from "../repositories/checkUserSessionInCache.repository";
export const checkUserSessionInCacheService = async ( export const checkUserSessionInCacheService = async (
userId: string, userId: string,
sessionId: string sessionId: string
) => { ) => {
try { try {
// Construct the Redis key name using the userId and sessionId // Construct the Redis key name using the userId and sessionId
const redisKeyName = `${process.env.app_name}:users:${userId}:sessions:${sessionId}`; const redisKeyName = `${process.env.app_name}:users:${userId}:sessions:${sessionId}`;
// Check if the user session exists in Redis // Check if the user session exists in Redis
const userSessionInRedis = await checkUserSessionInCacheRepo(redisKeyName); const userSessionInRedis = await checkUserSessionInCacheRepo(redisKeyName);
return userSessionInRedis; return userSessionInRedis;
} catch (error) { } catch (error) {
// Forward the error with a 400 status code and a message // Forward the error with a 400 status code and a message
ErrorForwarder(error, 400, "Bad Request"); ErrorForwarder(error, 400, "Bad Request");
} }
}; };

View File

@ -1,27 +1,27 @@
import { createUserSessionServiceParams } from "../userSession.types"; import { createUserSessionServiceParams } from "../userSession.types";
import { createUserSessionRepo } from "../repositories/insertUserSessionToDB.repository"; import { createUserSessionRepo } from "../repositories/insertUserSessionToDB.repository";
import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository"; import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository";
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder"; import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
export const createUserSessionService = async ( export const createUserSessionService = async (
data: createUserSessionServiceParams data: createUserSessionServiceParams
) => { ) => {
const sessionLifetime = Number(process.env.SESSION_EXPIRE!); const sessionLifetime = Number(process.env.SESSION_EXPIRE!);
try { try {
const newUserSession = await createUserSessionRepo({ const newUserSession = await createUserSessionRepo({
userId: data.userId, userId: data.userId,
isAuthenticated: true, isAuthenticated: true,
deviceType: data.userHeaderInformation.deviceType, deviceType: data.userHeaderInformation.deviceType,
deviceOs: data.userHeaderInformation.deviceOS, deviceOs: data.userHeaderInformation.deviceOS,
deviceIp: data.userHeaderInformation.ip, deviceIp: data.userHeaderInformation.ip,
validUntil: new Date(new Date().getTime() + sessionLifetime * 1000), validUntil: new Date(new Date().getTime() + sessionLifetime * 1000),
}); });
const timeExpires = Number(process.env.SESSION_EXPIRE!); const timeExpires = Number(process.env.SESSION_EXPIRE!);
await storeUserSessionToCacheRepo(newUserSession, timeExpires); await storeUserSessionToCacheRepo(newUserSession, timeExpires);
return newUserSession; return newUserSession;
} catch (error) { } catch (error) {
ErrorForwarder(error); ErrorForwarder(error);
} }
}; };

View File

@ -1,23 +1,23 @@
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder"; import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
import { findUniqueUserSessionInDBRepo } from "../repositories/findUniqueUserSessionInDB.repository"; import { findUniqueUserSessionInDBRepo } from "../repositories/findUniqueUserSessionInDB.repository";
export const getUserSessionFromDBService = async (identifier: string) => { export const getUserSessionFromDBService = async (identifier: string) => {
try { try {
// Check is session exists in DB // Check is session exists in DB
const userSession = await findUniqueUserSessionInDBRepo(identifier); const userSession = await findUniqueUserSessionInDBRepo(identifier);
// If session not found, return false // If session not found, return false
if ( if (
!userSession || !userSession ||
!userSession.isAuthenticated || !userSession.isAuthenticated ||
new Date(userSession.validUntil) < new Date() new Date(userSession.validUntil) < new Date()
) )
return false; return false;
// If session found, return it // If session found, return it
return userSession; return userSession;
} catch (error) { } catch (error) {
// If any DB error occurs, throw an AppError // If any DB error occurs, throw an AppError
ErrorForwarder(error, 401, "Unable to get user session"); ErrorForwarder(error, 401, "Unable to get user session");
} }
}; };

View File

@ -1,17 +1,17 @@
import { Prisma } from "@prisma/client"; import { Prisma } from "@prisma/client";
import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository"; import { storeUserSessionToCacheRepo } from "../repositories/storeUserSessionToCache.repository";
import { ErrorForwarder } from "../../../helpers/error/instances/forwarder"; import { ErrorForwarder } from "../../../helpers/error/instances/forwarder";
export const storeUserSessionToCacheService = async ( export const storeUserSessionToCacheService = async (
userSession: Prisma.UserSessionUncheckedCreateInput, userSession: Prisma.UserSessionUncheckedCreateInput,
timeExpires: number timeExpires: number
) => { ) => {
try { try {
// Store user session in cache with expiration time // Store user session in cache with expiration time
await storeUserSessionToCacheRepo(userSession, timeExpires); await storeUserSessionToCacheRepo(userSession, timeExpires);
return; return;
} catch (error) { } catch (error) {
// If any error occurs while storing session in cache, throw an AppError // If any error occurs while storing session in cache, throw an AppError
ErrorForwarder(error, 401, "Failed to store user session to cache"); ErrorForwarder(error, 401, "Failed to store user session to cache");
} }
}; };

View File

@ -1,3 +1,3 @@
import { prisma } from "../../utils/databases/prisma/connection"; import { prisma } from "../../utils/databases/prisma/connection";
export const userSessionModel = prisma.userSession; export const userSessionModel = prisma.userSession;

View File

@ -1,6 +1,6 @@
import { UserHeaderInformation } from "../../helpers/http/userHeader/getUserHeaderInformation/types"; import { UserHeaderInformation } from "../../helpers/http/userHeader/getUserHeaderInformation/types";
export interface createUserSessionServiceParams { export interface createUserSessionServiceParams {
userId: string; userId: string;
userHeaderInformation: UserHeaderInformation; userHeaderInformation: UserHeaderInformation;
} }

View File

@ -1,3 +1,3 @@
import { PrismaClient } from "@prisma/client"; import { PrismaClient } from "@prisma/client";
export const prisma = new PrismaClient(); export const prisma = new PrismaClient();

View File

@ -1,225 +1,225 @@
/** /**
* Map of known Prisma error codes to HTTP status codes and messages. * Map of known Prisma error codes to HTTP status codes and messages.
* Extend this map to handle additional error codes if needed. * Extend this map to handle additional error codes if needed.
*/ */
export const PrismaErrorCodeList: Record< export const PrismaErrorCodeList: Record<
string, string,
{ status: number; message: string } { status: number; message: string }
> = { > = {
P1000: { P1000: {
status: 500, status: 500,
message: `Authentication failed against the database server.`, message: `Authentication failed against the database server.`,
}, },
P1001: { P1001: {
status: 503, status: 503,
message: `Can't reach database server at ${process.env.APP_NAME}.`, message: `Can't reach database server at ${process.env.APP_NAME}.`,
}, },
P1002: { P1002: {
status: 503, status: 503,
message: `The database server was reached but timed out.`, message: `The database server was reached but timed out.`,
}, },
P1003: { P1003: {
status: 500, status: 500,
message: `Database does not exist.`, message: `Database does not exist.`,
}, },
P1008: { P1008: {
status: 504, status: 504,
message: `Operations timed out.`, message: `Operations timed out.`,
}, },
P1009: { P1009: {
status: 500, status: 500,
message: `Database requires SSL connection.`, message: `Database requires SSL connection.`,
}, },
P1010: { P1010: {
status: 403, status: 403,
message: `User was denied access to the database.`, message: `User was denied access to the database.`,
}, },
P1011: { P1011: {
status: 500, status: 500,
message: `Error opening a TLS connection.`, message: `Error opening a TLS connection.`,
}, },
P1012: { P1012: {
status: 500, status: 500,
message: `Schema validation error.`, message: `Schema validation error.`,
}, },
P1013: { P1013: {
status: 500, status: 500,
message: `Invalid Prisma schema.`, message: `Invalid Prisma schema.`,
}, },
P1014: { P1014: {
status: 500, status: 500,
message: `The underlying engine for the datasource could not be found.`, message: `The underlying engine for the datasource could not be found.`,
}, },
P1015: { P1015: {
status: 500, status: 500,
message: `Your Prisma schema is using features that are not supported for the database.`, message: `Your Prisma schema is using features that are not supported for the database.`,
}, },
P1016: { P1016: {
status: 500, status: 500,
message: `Your Prisma schema is using features that are not supported for the database version.`, message: `Your Prisma schema is using features that are not supported for the database version.`,
}, },
P1017: { P1017: {
status: 500, status: 500,
message: `The Prisma engine has crashed.`, message: `The Prisma engine has crashed.`,
}, },
P1018: { P1018: {
status: 500, status: 500,
message: `The current Prisma engine version is not compatible with the database.`, message: `The current Prisma engine version is not compatible with the database.`,
}, },
P1019: { P1019: {
status: 500, status: 500,
message: `The Prisma engine could not be started.`, message: `The Prisma engine could not be started.`,
}, },
P1020: { P1020: {
status: 500, status: 500,
message: `The Prisma engine exited with an error.`, message: `The Prisma engine exited with an error.`,
}, },
P1021: { P1021: {
status: 500, status: 500,
message: `The Prisma engine could not be started due to missing dependencies.`, message: `The Prisma engine could not be started due to missing dependencies.`,
}, },
P1022: { P1022: {
status: 500, status: 500,
message: `The Prisma engine could not be started due to an unknown error.`, message: `The Prisma engine could not be started due to an unknown error.`,
}, },
P2000: { P2000: {
status: 400, status: 400,
message: `The provided value for the column is too long for the column's type.`, message: `The provided value for the column is too long for the column's type.`,
}, },
P2001: { P2001: {
status: 404, status: 404,
message: `The record searched for in the where condition does not exist.`, message: `The record searched for in the where condition does not exist.`,
}, },
P2002: { P2002: {
status: 400, status: 400,
message: `Unique constraint failed on the fields.`, message: `Unique constraint failed on the fields.`,
}, },
P2003: { P2003: {
status: 400, status: 400,
message: `Foreign key constraint failed on the field.`, message: `Foreign key constraint failed on the field.`,
}, },
P2004: { P2004: {
status: 400, status: 400,
message: `A constraint failed on the database.`, message: `A constraint failed on the database.`,
}, },
P2005: { P2005: {
status: 400, status: 400,
message: `The value stored in the database for the field is invalid for the field's type.`, message: `The value stored in the database for the field is invalid for the field's type.`,
}, },
P2006: { P2006: {
status: 400, status: 400,
message: `The provided value for the field is not valid.`, message: `The provided value for the field is not valid.`,
}, },
P2007: { P2007: {
status: 400, status: 400,
message: `Data validation error.`, message: `Data validation error.`,
}, },
P2008: { P2008: {
status: 500, status: 500,
message: `Failed to parse the query.`, message: `Failed to parse the query.`,
}, },
P2009: { P2009: {
status: 400, status: 400,
message: `Failed to validate the query.`, message: `Failed to validate the query.`,
}, },
P2010: { P2010: {
status: 400, status: 400,
message: `Raw query failed.`, message: `Raw query failed.`,
}, },
P2011: { P2011: {
status: 400, status: 400,
message: `Null constraint violation on the field.`, message: `Null constraint violation on the field.`,
}, },
P2012: { P2012: {
status: 400, status: 400,
message: `Missing a required value.`, message: `Missing a required value.`,
}, },
P2013: { P2013: {
status: 400, status: 400,
message: `Missing the required argument.`, message: `Missing the required argument.`,
}, },
P2014: { P2014: {
status: 400, status: 400,
message: `The change you are trying to make would violate the required relation.`, message: `The change you are trying to make would violate the required relation.`,
}, },
P2015: { P2015: {
status: 404, status: 404,
message: `A related record could not be found.`, message: `A related record could not be found.`,
}, },
P2016: { P2016: {
status: 400, status: 400,
message: `Query interpretation error.`, message: `Query interpretation error.`,
}, },
P2017: { P2017: {
status: 400, status: 400,
message: `The records for the relation between the parent and child models were not connected.`, message: `The records for the relation between the parent and child models were not connected.`,
}, },
P2018: { P2018: {
status: 400, status: 400,
message: `The required connected records were not found.`, message: `The required connected records were not found.`,
}, },
P2019: { P2019: {
status: 400, status: 400,
message: `Input error.`, message: `Input error.`,
}, },
P2020: { P2020: {
status: 400, status: 400,
message: `Value out of range for the type.`, message: `Value out of range for the type.`,
}, },
P2021: { P2021: {
status: 400, status: 400,
message: `The table does not exist in the current database.`, message: `The table does not exist in the current database.`,
}, },
P2022: { P2022: {
status: 400, status: 400,
message: `The column does not exist in the current database.`, message: `The column does not exist in the current database.`,
}, },
P2023: { P2023: {
status: 400, status: 400,
message: `Inconsistent column data.`, message: `Inconsistent column data.`,
}, },
P2024: { P2024: {
status: 400, status: 400,
message: `Timed out fetching a new connection from the connection pool.`, message: `Timed out fetching a new connection from the connection pool.`,
}, },
P2025: { P2025: {
status: 404, status: 404,
message: `An operation failed because it depends on one or more records that were required but not found.`, message: `An operation failed because it depends on one or more records that were required but not found.`,
}, },
P2026: { P2026: {
status: 400, status: 400,
message: `The current database provider doesn't support a feature that the query uses.`, message: `The current database provider doesn't support a feature that the query uses.`,
}, },
P2027: { P2027: {
status: 400, status: 400,
message: `Multiple errors occurred on the database during query execution.`, message: `Multiple errors occurred on the database during query execution.`,
}, },
P2028: { P2028: {
status: 400, status: 400,
message: `Transaction API error.`, message: `Transaction API error.`,
}, },
P2029: { P2029: {
status: 400, status: 400,
message: `Query parameter limit exceeded.`, message: `Query parameter limit exceeded.`,
}, },
P2030: { P2030: {
status: 400, status: 400,
message: `Cannot find a fulltext index to use for the search.`, message: `Cannot find a fulltext index to use for the search.`,
}, },
P2031: { P2031: {
status: 400, status: 400,
message: `Prisma needs to perform a transaction, but the database does not support transactions.`, message: `Prisma needs to perform a transaction, but the database does not support transactions.`,
}, },
P2033: { P2033: {
status: 400, status: 400,
message: `A number used in the query does not fit into a 64-bit signed integer.`, message: `A number used in the query does not fit into a 64-bit signed integer.`,
}, },
P2034: { P2034: {
status: 503, status: 503,
message: `Too many connections are open to the database.`, message: `Too many connections are open to the database.`,
}, },
P2035: { P2035: {
status: 400, status: 400,
message: `A constraint failed on the database.`, message: `A constraint failed on the database.`,
}, },
}; };

View File

@ -1,11 +1,11 @@
/** /**
* @typedef {Object} ErrorResponse * @typedef {Object} ErrorResponse
* @property {number} status - The HTTP status code corresponding to the error. * @property {number} status - The HTTP status code corresponding to the error.
* @property {string} message - A human-readable error message. * @property {string} message - A human-readable error message.
* @property {any} [details] - Additional details about the error, if available. * @property {any} [details] - Additional details about the error, if available.
*/ */
export interface PrismaErrorTypes { export interface PrismaErrorTypes {
status: number; status: number;
message: string; message: string;
details?: any; details?: any;
} }

View File

@ -1,7 +1,7 @@
import Redis from "ioredis"; import Redis from "ioredis";
export const redis = new Redis({ export const redis = new Redis({
host: process.env.REDIS_HOST, host: process.env.REDIS_HOST,
port: Number(process.env.REDIS_PORT), port: Number(process.env.REDIS_PORT),
password: process.env.REDIS_PASSWORD, password: process.env.REDIS_PASSWORD,
}); });

View File

@ -1,16 +1,16 @@
src/ src/
└── modules/ └── modules/
└── movie/ └── movie/
├── controller/ ├── controller/
│ ├── createMovie.controller.ts │ ├── createMovie.controller.ts
│ ├── getAllMovies.controller.ts │ ├── getAllMovies.controller.ts
│ ├── getSimilarByGenre.controller.ts │ ├── getSimilarByGenre.controller.ts
├── services/ ├── services/
│ ├── createMovie.service.ts │ ├── createMovie.service.ts
│ ├── getAllMovies.service.ts │ ├── getAllMovies.service.ts
│ ├── getSimilarByGenre.service.ts │ ├── getSimilarByGenre.service.ts
├── movie.model.ts ├── movie.model.ts
├── movie.repository.ts ├── movie.repository.ts
├── movie.schema.ts ├── movie.schema.ts
├── movie.types.ts ├── movie.types.ts
└── index.ts └── index.ts

View File

@ -1,103 +1,103 @@
{ {
"compilerOptions": { "compilerOptions": {
/* Visit https://aka.ms/tsconfig to read more about this file */ /* Visit https://aka.ms/tsconfig to read more about this file */
/* Projects */ /* Projects */
// "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */ // "incremental": true, /* Save .tsbuildinfo files to allow for incremental compilation of projects. */
// "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */ // "composite": true, /* Enable constraints that allow a TypeScript project to be used with project references. */
// "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */ // "tsBuildInfoFile": "./.tsbuildinfo", /* Specify the path to .tsbuildinfo incremental compilation file. */
// "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */ // "disableSourceOfProjectReferenceRedirect": true, /* Disable preferring source files instead of declaration files when referencing composite projects. */
// "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */ // "disableSolutionSearching": true, /* Opt a project out of multi-project reference checking when editing. */
// "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */ // "disableReferencedProjectLoad": true, /* Reduce the number of projects loaded automatically by TypeScript. */
/* Language and Environment */ /* Language and Environment */
"target": "ES2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ "target": "ES2021", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */
// "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */ // "lib": [], /* Specify a set of bundled library declaration files that describe the target runtime environment. */
// "jsx": "preserve", /* Specify what JSX code is generated. */ // "jsx": "preserve", /* Specify what JSX code is generated. */
// "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */ // "experimentalDecorators": true, /* Enable experimental support for TC39 stage 2 draft decorators. */
// "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */ // "emitDecoratorMetadata": true, /* Emit design-type metadata for decorated declarations in source files. */
// "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */ // "jsxFactory": "", /* Specify the JSX factory function used when targeting React JSX emit, e.g. 'React.createElement' or 'h'. */
// "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */ // "jsxFragmentFactory": "", /* Specify the JSX Fragment reference used for fragments when targeting React JSX emit e.g. 'React.Fragment' or 'Fragment'. */
// "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */ // "jsxImportSource": "", /* Specify module specifier used to import the JSX factory functions when using 'jsx: react-jsx*'. */
// "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */ // "reactNamespace": "", /* Specify the object invoked for 'createElement'. This only applies when targeting 'react' JSX emit. */
// "noLib": true, /* Disable including any library files, including the default lib.d.ts. */ // "noLib": true, /* Disable including any library files, including the default lib.d.ts. */
// "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */ // "useDefineForClassFields": true, /* Emit ECMAScript-standard-compliant class fields. */
// "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */ // "moduleDetection": "auto", /* Control what method is used to detect module-format JS files. */
/* Modules */ /* Modules */
"module": "ES2022", /* Specify what module code is generated. */ "module": "ES2022", /* Specify what module code is generated. */
// "rootDir": "./", /* Specify the root folder within your source files. */ // "rootDir": "./", /* Specify the root folder within your source files. */
"moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */
// "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ // "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */
// "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */ // "paths": {}, /* Specify a set of entries that re-map imports to additional lookup locations. */
// "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */
// "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */ // "typeRoots": [], /* Specify multiple folders that act like './node_modules/@types'. */
"types": ["bun-types"], /* Specify type package names to be included without being referenced in a source file. */ "types": ["bun-types"], /* Specify type package names to be included without being referenced in a source file. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
// "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */ // "moduleSuffixes": [], /* List of file name suffixes to search when resolving a module. */
// "resolveJsonModule": true, /* Enable importing .json files. */ // "resolveJsonModule": true, /* Enable importing .json files. */
// "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */ // "noResolve": true, /* Disallow 'import's, 'require's or '<reference>'s from expanding the number of files TypeScript should add to a project. */
/* JavaScript Support */ /* JavaScript Support */
// "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */ // "allowJs": true, /* Allow JavaScript files to be a part of your program. Use the 'checkJS' option to get errors from these files. */
// "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */ // "checkJs": true, /* Enable error reporting in type-checked JavaScript files. */
// "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */ // "maxNodeModuleJsDepth": 1, /* Specify the maximum folder depth used for checking JavaScript files from 'node_modules'. Only applicable with 'allowJs'. */
/* Emit */ /* Emit */
// "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */ // "declaration": true, /* Generate .d.ts files from TypeScript and JavaScript files in your project. */
// "declarationMap": true, /* Create sourcemaps for d.ts files. */ // "declarationMap": true, /* Create sourcemaps for d.ts files. */
// "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */ // "emitDeclarationOnly": true, /* Only output d.ts files and not JavaScript files. */
// "sourceMap": true, /* Create source map files for emitted JavaScript files. */ // "sourceMap": true, /* Create source map files for emitted JavaScript files. */
// "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */ // "outFile": "./", /* Specify a file that bundles all outputs into one JavaScript file. If 'declaration' is true, also designates a file that bundles all .d.ts output. */
// "outDir": "./", /* Specify an output folder for all emitted files. */ // "outDir": "./", /* Specify an output folder for all emitted files. */
// "removeComments": true, /* Disable emitting comments. */ // "removeComments": true, /* Disable emitting comments. */
// "noEmit": true, /* Disable emitting files from a compilation. */ // "noEmit": true, /* Disable emitting files from a compilation. */
// "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */ // "importHelpers": true, /* Allow importing helper functions from tslib once per project, instead of including them per-file. */
// "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */ // "importsNotUsedAsValues": "remove", /* Specify emit/checking behavior for imports that are only used for types. */
// "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */ // "downlevelIteration": true, /* Emit more compliant, but verbose and less performant JavaScript for iteration. */
// "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */ // "sourceRoot": "", /* Specify the root path for debuggers to find the reference source code. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */ // "inlineSourceMap": true, /* Include sourcemap files inside the emitted JavaScript. */
// "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */ // "inlineSources": true, /* Include source code in the sourcemaps inside the emitted JavaScript. */
// "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */ // "emitBOM": true, /* Emit a UTF-8 Byte Order Mark (BOM) in the beginning of output files. */
// "newLine": "crlf", /* Set the newline character for emitting files. */ // "newLine": "crlf", /* Set the newline character for emitting files. */
// "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */ // "stripInternal": true, /* Disable emitting declarations that have '@internal' in their JSDoc comments. */
// "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */ // "noEmitHelpers": true, /* Disable generating custom helper functions like '__extends' in compiled output. */
// "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */ // "noEmitOnError": true, /* Disable emitting files if any type checking errors are reported. */
// "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */ // "preserveConstEnums": true, /* Disable erasing 'const enum' declarations in generated code. */
// "declarationDir": "./", /* Specify the output directory for generated declaration files. */ // "declarationDir": "./", /* Specify the output directory for generated declaration files. */
// "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */ // "preserveValueImports": true, /* Preserve unused imported values in the JavaScript output that would otherwise be removed. */
/* Interop Constraints */ /* Interop Constraints */
// "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */ // "isolatedModules": true, /* Ensure that each file can be safely transpiled without relying on other imports. */
// "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */ // "allowSyntheticDefaultImports": true, /* Allow 'import x from y' when a module doesn't have a default export. */
"esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */ "esModuleInterop": true, /* Emit additional JavaScript to ease support for importing CommonJS modules. This enables 'allowSyntheticDefaultImports' for type compatibility. */
// "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */ // "preserveSymlinks": true, /* Disable resolving symlinks to their realpath. This correlates to the same flag in node. */
"forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */ "forceConsistentCasingInFileNames": true, /* Ensure that casing is correct in imports. */
/* Type Checking */ /* Type Checking */
"strict": true, /* Enable all strict type-checking options. */ "strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */ // "noImplicitAny": true, /* Enable error reporting for expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */ // "strictNullChecks": true, /* When type checking, take into account 'null' and 'undefined'. */
// "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */ // "strictFunctionTypes": true, /* When assigning functions, check to ensure parameters and the return values are subtype-compatible. */
// "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */ // "strictBindCallApply": true, /* Check that the arguments for 'bind', 'call', and 'apply' methods match the original function. */
// "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */ // "strictPropertyInitialization": true, /* Check for class properties that are declared but not set in the constructor. */
// "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */ // "noImplicitThis": true, /* Enable error reporting when 'this' is given the type 'any'. */
// "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */ // "useUnknownInCatchVariables": true, /* Default catch clause variables as 'unknown' instead of 'any'. */
// "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */ // "alwaysStrict": true, /* Ensure 'use strict' is always emitted. */
// "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */ // "noUnusedLocals": true, /* Enable error reporting when local variables aren't read. */
// "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */ // "noUnusedParameters": true, /* Raise an error when a function parameter isn't read. */
// "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */ // "exactOptionalPropertyTypes": true, /* Interpret optional property types as written, rather than adding 'undefined'. */
// "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */ // "noImplicitReturns": true, /* Enable error reporting for codepaths that do not explicitly return in a function. */
// "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */ // "noFallthroughCasesInSwitch": true, /* Enable error reporting for fallthrough cases in switch statements. */
// "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */ // "noUncheckedIndexedAccess": true, /* Add 'undefined' to a type when accessed using an index. */
// "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */ // "noImplicitOverride": true, /* Ensure overriding members in derived classes are marked with an override modifier. */
// "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */ // "noPropertyAccessFromIndexSignature": true, /* Enforces using indexed accessors for keys declared using an indexed type. */
// "allowUnusedLabels": true, /* Disable error reporting for unused labels. */ // "allowUnusedLabels": true, /* Disable error reporting for unused labels. */
// "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */ // "allowUnreachableCode": true, /* Disable error reporting for unreachable code. */
/* Completeness */ /* Completeness */
// "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */ // "skipDefaultLibCheck": true, /* Skip type checking .d.ts files that are included with TypeScript. */
"skipLibCheck": true /* Skip type checking all .d.ts files. */ "skipLibCheck": true /* Skip type checking all .d.ts files. */
} }
} }