Skip to content

Commit

Permalink
feat(admin): separate nested resources
Browse files Browse the repository at this point in the history
  • Loading branch information
fieztazica committed Jun 10, 2024
1 parent 19d3d0b commit 45c18ba
Show file tree
Hide file tree
Showing 9 changed files with 278 additions and 178 deletions.
75 changes: 0 additions & 75 deletions apps/api/src/admin/admin.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,91 +8,16 @@ import {
Render,
Req,
Res,
UseGuards,
} from '@nestjs/common';
import { Request } from 'express';
import { RedirectAuth } from 'src/auth/decorator/redirectAuth.decorator';
import { RolesGuard } from 'src/auth/guard/roles.guard';
import { AdminService } from './admin.service';
import { DetailPage, EntityNames, MainLayoutRes } from './admin.type';
import { OrderStatus } from '@prisma/client';

@Controller('admin')
@UseGuards(RolesGuard)
export class AdminController {
constructor(private readonly adminService: AdminService) {}

@Post('configs/about/edit')
@RedirectAuth()
async postAboutPage(@Req() req, @Res() res, @Body() body: { about: string }) {
await this.adminService.setAbout(body.about);
res.redirect('/admin/configs/about/edit?successMessage=Saved');
}

@Get('configs/about/edit')
@RedirectAuth()
@Render('about/edit')
async editAboutPage(
@Req() req,
@Query('successMessage') successMessage: string,
) {
return {
successMessage: successMessage ? decodeURIComponent(successMessage) : '',
userinfo: req?.user?.userinfo,
data: await this.adminService.getAbout(),
};
}

@Post('orders/:orderId/status')
@RedirectAuth()
async postOrderStatus(
@Req() req,
@Res() res,
@Param('orderId') orderId: string,
@Query('data') data: keyof typeof OrderStatus,
@Query('page') page: number = 1,
@Query('perPage') perPage: number = 10,
@Query('order') order: 'desc' | 'asc' = 'desc',
@Query('sort') sort: string = 'createdAt',
) {
const { status } = await this.adminService.updateOrderStatus(orderId, data);
const successMessage = encodeURIComponent(
`Updated order status! - ${status}`,
);
const searchParams = new URLSearchParams({
orderId,
successMessage,
page: page.toString(),
perPage: perPage.toString(),
order,
sort,
});
res.redirect(`/admin/orders?${searchParams.toString()}`);
}

@Get('orders')
@RedirectAuth()
@Render('order/list')
async listOrdersPage(
@Req() req: Request,
@Query('page') page: number = 1,
@Query('perPage') perPage: number = 10,
@Query('successMessage') successMessage: string,
@Query('order') order: 'desc' | 'asc' = 'desc',
@Query('sort') sort: string = 'createdAt',
@Query('orderId') orderId?: string,
) {
return this.adminService.orderListRes(
req,
page,
perPage,
successMessage,
sort,
order,
orderId,
);
}

@Get()
@Render('home')
home(@Req() req) {
Expand Down
14 changes: 12 additions & 2 deletions apps/api/src/admin/admin.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,11 @@ import { OrdersModule } from 'src/orders/orders.module';
import { ProductsModule } from 'src/products/products.module';
import { AdminController } from './admin.controller';
import { AdminService } from './admin.service';
import { AdminProductsController } from './products/admin.products.controller';
import { AdminOrdersController } from './orders/admin.orders.controller';
import { AdminOrdersService } from './orders/admin.orders.service';
import { AdminConfigsController } from './configs/admin.configs.controller';
import { AdminConfigsService } from './configs/admin.configs.service';

@Module({
imports: [
Expand All @@ -19,7 +24,12 @@ import { AdminService } from './admin.service';
OrdersModule,
ConfigsModule,
],
controllers: [AdminController],
providers: [AdminService],
controllers: [
AdminConfigsController,
AdminProductsController,
AdminOrdersController,
AdminController,
],
providers: [AdminService, AdminOrdersService, AdminConfigsService],
})
export class AdminModule {}
101 changes: 0 additions & 101 deletions apps/api/src/admin/admin.service.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import { Body, Injectable, Req, Res } from '@nestjs/common';
import { OrderStatus } from '@prisma/client';
import dayjs from 'dayjs';
import calendar from 'dayjs/plugin/calendar';
import timezone from 'dayjs/plugin/timezone';
Expand Down Expand Up @@ -260,97 +259,6 @@ export class AdminService {
};
}

async orderListRes(
@Req() req: Request,
page: number,
perPage: number,
successMessage: string,
sort: string = 'createdAt',
order: 'desc' | 'asc' = 'desc',
orderId?: string,
): Promise<ListViewRes | MainLayoutRes> {
const entityService = this.ordersService;

let paginatedRes;
let entityRecords;
let errorMessage = '';
let orderItems = [];
try {
paginatedRes = await entityService.paginatedFindAll(
{
page,
perPage,
},
{
orderBy: {
[sort]: order,
},
},
);
entityRecords = paginatedRes.data;
entityRecords.forEach((record) => {
this.filterFieldsFromEntity(
this.beautifyEntity(record),
['id', 'total', 'status', 'createdAt'],
false,
);
});
} catch (error) {
errorMessage = `Failed to fetch orders records`;
console.error(`${errorMessage}:`, error);
return {
errorMessage,
userinfo: req.user?.userinfo,
resourceName: 'orders',
};
}

let uniqueKeys;
try {
uniqueKeys = this.getUniqueKeys(entityRecords);
} catch (error) {
errorMessage = `Failed to get unique keys for orders records`;
console.error(`${errorMessage}:`, error);
return {
errorMessage,
userinfo: req.user?.userinfo,
};
}

const searchParams = new URLSearchParams({
page: page.toString(),
perPage: perPage.toString(),
sort,
order,
});

if (orderId) {
orderItems = await this.ordersService.getOrderItems(orderId);
}

return {
heading: convertCamelCaseToTitleCase('orders'),
resourceName: 'orders',
uniqueKeys,
data: entityRecords,
meta: paginatedRes.meta,
userinfo: req.user?.userinfo,
successMessage: successMessage ? decodeURIComponent(successMessage) : '',
order,
sort,
orderItems,
orderId,
searchParams: searchParams.toString(),
};
}

async updateOrderStatus(orderId: string, status: keyof typeof OrderStatus) {
return await this.ordersService.update(orderId, {
id: orderId,
status: OrderStatus[status],
});
}

async getCreateInputFromBody(
@Body() body,
entityName?: EntityNames,
Expand Down Expand Up @@ -513,13 +421,4 @@ export class AdminService {
};
}
}

async getAbout() {
const result = await this.configsService.getOrSet('about', '');
return result;
}

async setAbout(content: string) {
return await this.configsService.set('about', content);
}
}
42 changes: 42 additions & 0 deletions apps/api/src/admin/configs/admin.configs.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import {
Body,
Controller,
Get,
Post,
Query,
Render,
Req,
Res,
} from '@nestjs/common';
import { Request } from 'express';
import { RedirectAuth } from 'src/auth/decorator/redirectAuth.decorator';
import { AdminConfigsService } from './admin.configs.service';

@Controller('admin/configs')
export class AdminConfigsController {
constructor(private readonly adminConfigsService: AdminConfigsService) {}

@Post('about/edit')
async postAboutPage(
@Req() req: Request,
@Res() res,
@Body() body: { about: string },
) {
await this.adminConfigsService.setAbout(body.about);
res.redirect('/admin/configs/about/edit?successMessage=Saved');
}

@Get('about/edit')
@RedirectAuth()
@Render('about/edit')
async editAboutPage(
@Req() req: Request,
@Query('successMessage') successMessage: string,
) {
return {
successMessage: successMessage ? decodeURIComponent(successMessage) : '',
userinfo: req?.user?.userinfo,
data: await this.adminConfigsService.getAbout(),
};
}
}
16 changes: 16 additions & 0 deletions apps/api/src/admin/configs/admin.configs.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { Injectable } from '@nestjs/common';
import { ConfigsService } from 'src/configs/configs.service';

@Injectable()
export class AdminConfigsService {
constructor(private readonly configsService: ConfigsService) {}

async getAbout() {
const result = await this.configsService.getOrSet('about', '');
return result;
}

async setAbout(content: string) {
return await this.configsService.set('about', content);
}
}
Loading

0 comments on commit 45c18ba

Please sign in to comment.