Skip to content

Commit

Permalink
Merge pull request #20 from erik1110/feature/api
Browse files Browse the repository at this point in the history
[style] adjust style
  • Loading branch information
erik1110 committed Jan 24, 2024
2 parents 327a738 + 1cf43f7 commit bea3594
Show file tree
Hide file tree
Showing 38 changed files with 855 additions and 713 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/main.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ jobs:

- name: NPM install, build and test
run: |
npm install --force
npm install
npm run build --if-present
npm run test --if-present
env:
Expand Down
15 changes: 2 additions & 13 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,6 @@
"firebase-admin": "^12.0.0",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.1.0",
"mongoose-auto-increment": "^5.0.1",
"nestjs-object-id": "^1.2.0",
"nodemailer": "^6.9.7",
"passport": "^0.7.0",
Expand Down
2 changes: 1 addition & 1 deletion src/app.controller.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ describe('AppController', () => {
expect(appController.root()).toBe('Health Check');
});
});
});
});
52 changes: 30 additions & 22 deletions src/common/decorators/validation/dto.decorator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
import { ValidationOptions, registerDecorator, ValidationArguments } from "class-validator";
import {
ValidationOptions,
registerDecorator,
ValidationArguments,
} from 'class-validator';

export function IsNotBeforeToday(validationOptions?: ValidationOptions): PropertyDecorator {
export function IsNotBeforeToday(
validationOptions?: ValidationOptions,
): PropertyDecorator {
return function (object: Record<string, any>, propertyName: string) {
registerDecorator({
name: 'isNotBeforeToday',
Expand All @@ -20,24 +26,26 @@ export function IsNotBeforeToday(validationOptions?: ValidationOptions): Propert
};
}


export function IsBefore(property: string, validationOptions?: ValidationOptions) {
return function (object: Record<string, any>, propertyName: string) {
registerDecorator({
name: 'isBefore',
target: object.constructor,
propertyName: propertyName,
constraints: [property],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments): boolean {
const relatedValue = args.object[property];
if (value instanceof Date && relatedValue instanceof Date) {
return value > relatedValue;
}
return false;
},
export function IsBefore(
property: string,
validationOptions?: ValidationOptions,
) {
return function (object: Record<string, any>, propertyName: string) {
registerDecorator({
name: 'isBefore',
target: object.constructor,
propertyName: propertyName,
constraints: [property],
options: validationOptions,
validator: {
validate(value: any, args: ValidationArguments): boolean {
const relatedValue = args.object[property];
if (value instanceof Date && relatedValue instanceof Date) {
return value > relatedValue;
}
return false;
},
});
};
}
},
});
};
}
36 changes: 18 additions & 18 deletions src/features/culinary/culinary.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import {
import { IsObjectIdPipe } from 'nestjs-object-id';
import { AuthGuard } from '@nestjs/passport';


@ApiTags('Home/Culinary - 美味佳餚')
@ApiErrorDecorator(
HttpStatus.INTERNAL_SERVER_ERROR,
Expand All @@ -44,25 +43,26 @@ import { AuthGuard } from '@nestjs/passport';
@ApiBearerAuth()
@Controller('/api/v1/home/culinary')
export class CulinaryController {
constructor(private readonly culinaryService: CulinaryService) {}
constructor(private readonly culinaryService: CulinaryService) {}

@Get('')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: '取得所有美味佳餚 Get all delicious dishes' })
@ApiOkResponse({ type: GetCulinarySuccessDto })
async getallCulinary(@Req() req: Request) {
return await this.culinaryService.getallCulinary(req);
}
@Get('')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: '取得所有美味佳餚 Get all delicious dishes' })
@ApiOkResponse({ type: GetCulinarySuccessDto })
async getallCulinary(@Req() req: Request) {
return await this.culinaryService.getallCulinary(req);
}

@Get(':id')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: '取得單筆美味佳餚 Get one delicious dish' })
@ApiOkResponse({ type: GetOneCulinarySuccessDto })
async getOneCulinary(
@Param('id', IsObjectIdPipe) id: string,
@Req() req: Request) {
return await this.culinaryService.getOneCulinary(id, req);
}
@Get(':id')
@HttpCode(HttpStatus.OK)
@ApiOperation({ summary: '取得單筆美味佳餚 Get one delicious dish' })
@ApiOkResponse({ type: GetOneCulinarySuccessDto })
async getOneCulinary(
@Param('id', IsObjectIdPipe) id: string,
@Req() req: Request,
) {
return await this.culinaryService.getOneCulinary(id, req);
}
}

@ApiTags('Admin/Culinary - 美味佳餚管理')
Expand Down
5 changes: 4 additions & 1 deletion src/features/culinary/culinary.module.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { Module } from '@nestjs/common';
import { CulinaryAdminController, CulinaryController } from './culinary.controller';
import {
CulinaryAdminController,
CulinaryController,
} from './culinary.controller';
import { CulinaryService } from './culinary.service';
import { CulinarySchema } from './schemas/culinary.schema';
import { MongooseModule } from '@nestjs/mongoose';
Expand Down
2 changes: 1 addition & 1 deletion src/features/culinary/culinary.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export class CulinaryService {

async getallCulinary(req: Request) {
const result = await this.culinaryModel.find();
const ids = result.map(order => order._id.toString());
const ids = result.map((order) => order._id.toString());
return getHttpResponse.successResponse({
message: '取得所有美味佳餚',
data: ids,
Expand Down
4 changes: 1 addition & 3 deletions src/features/culinary/dto/culinary.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,9 +114,7 @@ export class GetCulinarySuccessDto {
message: string;

@ApiProperty({
example: [
"658e985c1c91c1765e2972b5",
],
example: ['658e985c1c91c1765e2972b5'],
})
data: object;
}
Expand Down
28 changes: 14 additions & 14 deletions src/features/image/dto/fileUpload.dto.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,19 @@
import { ApiProperty } from "@nestjs/swagger";
import { ApiProperty } from '@nestjs/swagger';

export class FileUploadDto {
@ApiProperty({ type: 'string', format: 'binary' })
file: any;
@ApiProperty({ type: 'string', format: 'binary' })
file: any;
}

export class GetImageSuccessDto {
@ApiProperty({ example: true })
status: boolean;
@ApiProperty({ example: '取得圖片網址' })
message: string;
@ApiProperty({
example: "http://localhost:3000/api/v1/url/HSIARDTXC"
})
data: object;
}
@ApiProperty({ example: true })
status: boolean;

@ApiProperty({ example: '取得圖片網址' })
message: string;

@ApiProperty({
example: 'http://localhost:3000/api/v1/url/HSIARDTXC',
})
data: object;
}
49 changes: 26 additions & 23 deletions src/features/image/firebase.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,30 +3,33 @@ import * as admin from 'firebase-admin';

@Injectable()
export class FirebaseService {
private readonly storage: admin.storage.Storage;
private readonly storage: admin.storage.Storage;

readonly firebase_params = {
type: process.env.FIREBASE_TYPE,
project_id: process.env.FIREBASE_PROJECT_ID,
private_key_id: process.env.FIREBASE_PRIVATE_KEY_ID,
private_key: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
client_email: process.env.FIREBASE_CLIENT_EMAIL,
client_id: process.env.FIREBASE_CLIENT_ID,
auth_uri: process.env.FIREBASE_AUTH_URI,
token_uri: process.env.FIREBASE_TOKEN_URI,
auth_provider_X509_cert_url: process.env.FIREBASE_AUTH_PROVIDER_X509_CERT_URL,
client_x509_cert_url: process.env.FIREBASE_CLIENT_X509_CERT_URL,
};
readonly firebase_params = {
type: process.env.FIREBASE_TYPE,
project_id: process.env.FIREBASE_PROJECT_ID,
private_key_id: process.env.FIREBASE_PRIVATE_KEY_ID,
private_key: process.env.FIREBASE_PRIVATE_KEY.replace(/\\n/g, '\n'),
client_email: process.env.FIREBASE_CLIENT_EMAIL,
client_id: process.env.FIREBASE_CLIENT_ID,
auth_uri: process.env.FIREBASE_AUTH_URI,
token_uri: process.env.FIREBASE_TOKEN_URI,
auth_provider_X509_cert_url:
process.env.FIREBASE_AUTH_PROVIDER_X509_CERT_URL,
client_x509_cert_url: process.env.FIREBASE_CLIENT_X509_CERT_URL,
};

constructor(){
admin.initializeApp({
credential: admin.credential.cert(this.firebase_params as admin.ServiceAccount),
storageBucket: `${process.env.FIREBASE_PROJECT_ID}.appspot.com`,
});
this.storage = admin.storage();
}
constructor() {
admin.initializeApp({
credential: admin.credential.cert(
this.firebase_params as admin.ServiceAccount,
),
storageBucket: `${process.env.FIREBASE_PROJECT_ID}.appspot.com`,
});
this.storage = admin.storage();
}

getStorageInstance(): admin.storage.Storage{
return this.storage;
}
getStorageInstance(): admin.storage.Storage {
return this.storage;
}
}
75 changes: 45 additions & 30 deletions src/features/image/image.controller.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,21 @@
import { Controller, Get, HttpStatus, Param, Post, Res, UploadedFile, UseGuards, UseInterceptors } from '@nestjs/common';
import {
Controller,
HttpStatus,
Post,
UploadedFile,
UseGuards,
UseInterceptors,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ImageService } from './image.service';
import { ApiBearerAuth, ApiBody, ApiConsumes, ApiOkResponse, ApiOperation, ApiTags } from '@nestjs/swagger';
import {
ApiBearerAuth,
ApiBody,
ApiConsumes,
ApiCreatedResponse,
ApiOperation,
ApiTags,
} from '@nestjs/swagger';
import { FileUploadDto, GetImageSuccessDto } from './dto/fileUpload.dto';
import { UrlService } from '../url/url.service';
import { AuthGuard } from '@nestjs/passport';
Expand All @@ -18,34 +32,35 @@ import { getHttpResponse } from 'src/utils/successHandler';
@ApiBearerAuth()
@Controller('/api/v1/image')
export class ImageController {
constructor(
private readonly imageService: ImageService,
private readonly urlService: UrlService,
) {}
constructor(
private readonly imageService: ImageService,
private readonly urlService: UrlService,
) {}

@Post('upload')
@UseInterceptors(FileInterceptor('file'))
@ApiConsumes('multipart/form-data')
@ApiOperation({ summary: '上傳圖片 Upload an image' })
@ApiOkResponse({ type: GetImageSuccessDto })
@ApiBody({
description: "網址會由該服務進行轉址 The URL will be redirected by the service.",
type: FileUploadDto,
})
async uploadImage(@UploadedFile() file){
const imageUrl = await this.imageService.uploadImage(file);
let shortenUrl = await this.urlService.shortenUrl(imageUrl)
if (process.env.NODE_ENV === 'dev') {
shortenUrl = `http://localhost:${process.env.PORT}/api/v1/url/`;
} else {
shortenUrl = `${process.env.PRODUCTION_URL}/api/v1/url/`;
}

const shortenedUrl = await this.urlService.shortenUrl(imageUrl);
const redirectUrl = shortenUrl + shortenedUrl;
return getHttpResponse.successResponse({
message: '取得圖片網址',
data: redirectUrl,
});
@Post('upload')
@UseInterceptors(FileInterceptor('file'))
@ApiConsumes('multipart/form-data')
@ApiOperation({ summary: '上傳圖片 Upload an image' })
@ApiCreatedResponse({ type: GetImageSuccessDto })
@ApiBody({
description:
'網址會由該服務進行轉址 The URL will be redirected by the service.',
type: FileUploadDto,
})
async uploadImage(@UploadedFile() file) {
const imageUrl = await this.imageService.uploadImage(file);
let shortenUrl = await this.urlService.shortenUrl(imageUrl);
if (process.env.NODE_ENV === 'dev') {
shortenUrl = `http://localhost:${process.env.PORT}/api/v1/url/`;
} else {
shortenUrl = `${process.env.PRODUCTION_URL}/api/v1/url/`;
}

const shortenedUrl = await this.urlService.shortenUrl(imageUrl);
const redirectUrl = shortenUrl + shortenedUrl;
return getHttpResponse.successResponse({
message: '取得圖片網址',
data: redirectUrl,
});
}
}
3 changes: 1 addition & 2 deletions src/features/image/image.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,11 @@ import { Module } from '@nestjs/common';
import { FirebaseService } from './firebase.service';
import { ImageService } from './image.service';
import { ImageController } from './image.controller';
import { UrlService } from '../url/url.service';
import { UrlModule } from '../url/url.module';

@Module({
imports: [UrlModule],
controllers: [ImageController],
providers: [FirebaseService, ImageService]
providers: [FirebaseService, ImageService],
})
export class ImageModule {}
Loading

0 comments on commit bea3594

Please sign in to comment.