Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

initial master item #1

Open
wants to merge 13 commits into
base: main
Choose a base branch
from
1 change: 0 additions & 1 deletion src/database/connection-mongodb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -185,7 +185,6 @@ export default class MongoDbConnection implements IDatabaseAdapter {
_id: "response.insertedId.toString()",
};
} catch (error) {
console.log(error);
if (error instanceof MongoServerError) {
throw new MongoError(error);
}
Expand Down
1 change: 0 additions & 1 deletion src/modules/auth/controllers/signin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import { db } from "@src/database/database.js";

export const signin = async (req: Request, res: Response, next: NextFunction) => {
try {
console.log(req.body);
validate(req.body);

const signinUserService = new SigninUserService(db);
Expand Down
2 changes: 1 addition & 1 deletion src/modules/auth/controllers/verify-token.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ export const verifyToken = async (req: Request, res: Response, next: NextFunctio
name: result.name,
email: result.email,
username: result.username,
role: result.role,
roleName: result.roleName,
});
} catch (error) {
next(error);
Expand Down
2 changes: 0 additions & 2 deletions src/modules/auth/services/read-user-by-email.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,6 @@ export class ReadUserByEmailService {
sort: "",
};

console.log(query);

const userRepository = new UserRepository(this.db);
const result = await userRepository.readMany(query);

Expand Down
3 changes: 2 additions & 1 deletion src/modules/auth/services/verify-token.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ export class VerifyTokenUserService {
name: user.name,
email: user.email,
username: user.username,
role: user.role,
roleName: user.role[0].name,
permissions: user.role[0].permissions,
googleDriveId: user.googleDriveId,
oauth: user.oauth,
};
Expand Down
39 changes: 39 additions & 0 deletions src/modules/item-group/controllers/create.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
import ApiError from "@point-hub/express-error-handler/lib/api-error.js";
import { NextFunction, Request, Response } from "express";
import { db } from "@src/database/database.js";
import { VerifyTokenUserService } from "@src/modules/auth/services/verify-token.service.js";
import { validate } from "@src/modules/item-group/request/item-group.request.js";
import { ItemGroupService } from "@src/modules/item-group/services/create.service.js";

export const create = async (req: Request, res: Response, next: NextFunction) => {
try {
const session = db.startSession();
db.startTransaction();
const verifyTokenService = new VerifyTokenUserService(db);
const createItemGroupService = new ItemGroupService(db);
const authorizationHeader = req.headers.authorization ?? "";

if (authorizationHeader === "") {
throw new ApiError(401, { message: "Unauthorized Access" });
}
const authUser = await verifyTokenService.handle(authorizationHeader);
const found = authUser.permissions.includes("create-item-group");
if (!found) {
throw new ApiError(403);
}

await validate(req.body, "create");
const userId: string = authUser._id?.toString() || "";
const result = await createItemGroupService.handle(userId, req.body, session);

await db.commitTransaction();
res.status(201).json({
_id: result._id,
});
} catch (error) {
await db.abortTransaction();
next(error);
} finally {
await db.endSession();
}
};
35 changes: 35 additions & 0 deletions src/modules/item-group/controllers/delete.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import ApiError from "@point-hub/express-error-handler/lib/api-error.js";
import { NextFunction, Request, Response } from "express";
import { db } from "@src/database/database.js";
import { VerifyTokenUserService } from "@src/modules/auth/services/verify-token.service.js";
import { DeleteItemGroupService } from "@src/modules/item-group/services/delete.service.js";

export const destroy = async (req: Request, res: Response, next: NextFunction) => {
try {
const session = db.startSession();
db.startTransaction();

const deleteItemGroupService = new DeleteItemGroupService(db);
const verifyTokenService = new VerifyTokenUserService(db);
const authorizationHeader = req.headers.authorization ?? "";

if (authorizationHeader === "") {
throw new ApiError(401, { message: "Unauthorized Access" });
}
const authUser = await verifyTokenService.handle(authorizationHeader);
const found = authUser.permissions.includes("delete-item-group");
if (!found) {
throw new ApiError(403);
}
await deleteItemGroupService.handle(req.params.id, { session });

await db.commitTransaction();

res.status(204).json();
} catch (error) {
await db.abortTransaction();
next(error);
} finally {
await db.endSession();
}
};
5 changes: 5 additions & 0 deletions src/modules/item-group/controllers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export { create } from "./create.controller.js";
export { destroy } from "./delete.controller.js";
export { read } from "./read.controller.js";
export { readMany } from "./read-many.controller.js";
export { update } from "./update.controller.js";
63 changes: 63 additions & 0 deletions src/modules/item-group/controllers/read-many.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import ApiError from "@point-hub/express-error-handler/lib/api-error.js";
import { NextFunction, Request, Response } from "express";
import { QueryInterface } from "@src/database/connection.js";
import { db } from "@src/database/database.js";
import { VerifyTokenUserService } from "@src/modules/auth/services/verify-token.service.js";

import { ItemGroupInterface } from "@src/modules/item-group/entities/item-group.entity.js";
import { ReadManyItemGroupService } from "@src/modules/item-group/services/read-many.service.js";

export interface PaginationInterface {
page: number;
pageCount: number;
pageSize: number;
totalDocument: number;
}

export interface ResponseInterface {
data: Array<ItemGroupInterface>;
pagination: PaginationInterface;
}

export const readMany = async (req: Request, res: Response, next: NextFunction) => {
try {
const authorizationHeader = req.headers.authorization ?? "";
const readManyItemGroupService = new ReadManyItemGroupService(db);
const tokenService = new VerifyTokenUserService(db);
if (authorizationHeader === "") {
throw new ApiError(401);
}

const authUser = await tokenService.handle(authorizationHeader);

const found = authUser.permissions.includes("read-item-group");
if (!found) {
throw new ApiError(403);
}
const iQuery: QueryInterface = {
fields: (req.query.field as string) ?? "",
filter: (req.query.filter as any) ?? {},
page: Number(req.query.page ?? 1),
pageSize: Number(req.query.pageSize ?? 10),
sort: (req.query.sort as string) ?? "",
};

const result = await readManyItemGroupService.handle(iQuery);

const pagination: PaginationInterface = {
page: result.pagination.page,
pageSize: result.pagination.pageSize,
pageCount: result.pagination.pageCount,
totalDocument: result.pagination.totalDocument,
};

const response: ResponseInterface = {
data: result.item,
pagination: pagination,
};

res.status(200).json(response);
} catch (error) {
next(error);
}
};
28 changes: 28 additions & 0 deletions src/modules/item-group/controllers/read.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import ApiError from "@point-hub/express-error-handler/lib/api-error.js";
import { NextFunction, Request, Response } from "express";
import { ReadItemGroupService } from "../services/read.service.js";
import { db } from "@src/database/database.js";
import { VerifyTokenUserService } from "@src/modules/auth/services/verify-token.service.js";

export const read = async (req: Request, res: Response, next: NextFunction) => {
try {
const authorizationHeader = req.headers.authorization ?? "";
const readItemService = new ReadItemGroupService(db);
const tokenService = new VerifyTokenUserService(db);
if (authorizationHeader === "") {
throw new ApiError(401);
}

const authUser = await tokenService.handle(authorizationHeader);

const found = authUser.permissions.includes("read-item-group");
if (!found) {
throw new ApiError(403);
}
const result = await readItemService.handle(req.params.id);

res.status(200).json({ data: result });
} catch (error) {
next(error);
}
};
40 changes: 40 additions & 0 deletions src/modules/item-group/controllers/update.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import ApiError from "@point-hub/express-error-handler/lib/api-error.js";
import { NextFunction, Request, Response } from "express";
import { UpdateItemGroupService } from "../services/update.service.js";
import { db } from "@src/database/database.js";
import { VerifyTokenUserService } from "@src/modules/auth/services/verify-token.service.js";
import { validate } from "@src/modules/item-group/request/item-group.request.js";

export const update = async (req: Request, res: Response, next: NextFunction) => {
try {
const session = db.startSession();

db.startTransaction();

const updateItemGroupService = new UpdateItemGroupService(db);
const verifyTokenService = new VerifyTokenUserService(db);
const authorizationHeader = req.headers.authorization ?? "";

if (authorizationHeader === "") {
throw new ApiError(401, { message: "Unauthorized Access" });
}
const authUser = await verifyTokenService.handle(authorizationHeader);
const found = authUser.permissions.includes("update-item-group");
if (!found) {
throw new ApiError(403);
}

await validate(req.body, "update");
const userId: string = authUser._id?.toString() || "";
await updateItemGroupService.handle(userId, req.params.id, req.body, session);

await db.commitTransaction();

res.status(204).json();
} catch (error) {
await db.abortTransaction();
next(error);
} finally {
await db.endSession();
}
};
18 changes: 18 additions & 0 deletions src/modules/item-group/entities/item-group.entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { ObjectId } from "mongodb";

export interface ItemGroupInterface {
_id?: string | ObjectId;
name?: string;
updatedBy_id?: string;
createdBy_id?: string;
createdAt?: Date;
updatedAt?: Date;
}

export class ItemGroupEntity {
public item: ItemGroupInterface;

constructor(item: ItemGroupInterface) {
this.item = item;
}
}
70 changes: 70 additions & 0 deletions src/modules/item-group/entities/item-group.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
import { IDatabaseAdapter } from "@src/database/connection";

export const name = "item_group";

export const restrictedFields = [];

const isExists = async (db: IDatabaseAdapter) => {
const collections = (await db.listCollections()) as [];
return collections.some(function (el: any) {
return el.name === name;
});
};

export async function createCollection(db: IDatabaseAdapter) {
try {
if (!(await isExists(db))) {
await db.createCollection(name);
}

await db.updateSchema(name, {
bsonType: "object",
required: ["name"],
properties: {
createdAt: {
bsonType: "date",
description: "must be a date and is required",
},
updatedAt: {
bsonType: "date",
description: "must be a date and is required",
},
name: {
bsonType: "string",
description: "must be a string and is required",
},
createdBy_id: {
bsonType: "string",
description: "must be a string and is required",
},
updatedBy_id: {
bsonType: "string",
description: "must be a string and is required",
},
},
});
await db.createIndex(
name,
{ name: -1 },
{
unique: true,
collation: {
locale: "en",
strength: 2,
},
}
);
} catch (error) {
throw error;
}
}

export async function dropCollection(db: IDatabaseAdapter) {
try {
if (await isExists(db)) {
await db.dropCollection(name);
}
} catch (error) {
throw error;
}
}
47 changes: 47 additions & 0 deletions src/modules/item-group/repositories/item-group.repository.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import { BaseRepository } from "@src/database/base-repository.js";
import DatabaseConnection, {
DocumentInterface,
CreateOptionsInterface,
CreateResultInterface,
ReadOptionsInterface,
ReadResultInterface,
QueryInterface,
ReadManyOptionsInterface,
ReadManyResultInterface,
UpdateOptionsInterface,
UpdateResultInterface,
DeleteOptionsInterface,
DeleteResultInterface,
} from "@src/database/connection";

export class ItemGroupRepository extends BaseRepository {
constructor(db: DatabaseConnection) {
super(db, "item_group");
}

public async create(doc: DocumentInterface, options?: CreateOptionsInterface): Promise<CreateResultInterface> {
return await this.collection().create(doc, options);
}

public async read(id: string, options?: ReadOptionsInterface): Promise<ReadResultInterface> {
return await this.collection().read(id, options);
}

public async readMany(query: QueryInterface, options?: ReadManyOptionsInterface): Promise<ReadManyResultInterface> {
return await this.collection().readMany(query, options);
}
public async update(
id: string,
document: DocumentInterface,
options?: UpdateOptionsInterface
): Promise<UpdateResultInterface> {
return await this.collection().update(id, document, options);
}

public async delete(id: string, options?: DeleteOptionsInterface): Promise<DeleteResultInterface> {
return await this.collection().delete(id, options);
}
public async aggregate(pipeline: any, query: any) {
return await this.collection().aggregate(pipeline, query);
}
}
Loading