Skip to content

Commit

Permalink
feat(server): implement & reafct app apis with server db (#462)
Browse files Browse the repository at this point in the history
Signed-off-by: maslow <wangfugen@126.com>
  • Loading branch information
maslow authored Dec 1, 2022
1 parent f900b29 commit d960382
Show file tree
Hide file tree
Showing 14 changed files with 212 additions and 73 deletions.
63 changes: 32 additions & 31 deletions server/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@
// learn more about it in the docs: https://pris.ly/d/prisma-schema

generator client {
provider = "prisma-client-js"
provider = "prisma-client-js"
previewFeatures = ["interactiveTransactions"]
}

datasource db {
Expand All @@ -11,23 +12,23 @@ datasource db {
}

model User {
id String @id @default(auto()) @map("_id") @db.ObjectId
username String @unique
email String @unique
phone String @unique
id String @id @default(auto()) @map("_id") @db.ObjectId
username String @unique
email String @unique
phone String @unique
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
profile UserProfile?
}

model UserProfile {
id String @id @default(auto()) @map("_id") @db.ObjectId
uid String @unique @db.ObjectId
openid String?
from String?
avatar String?
name String?
id String @id @default(auto()) @map("_id") @db.ObjectId
uid String @unique @db.ObjectId
openid String?
from String?
avatar String?
name String?
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
Expand All @@ -38,7 +39,7 @@ model Region {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String @unique
desc String?
applications Application[]
Application Application[]
}

model Bundle {
Expand All @@ -52,7 +53,7 @@ model Bundle {
networkTrafficOutbound Int
networkTrafficInbound Int?
priority Int
applications Application[]
Application Application[]
}

type RuntimeImageGroup {
Expand All @@ -62,13 +63,13 @@ type RuntimeImageGroup {
}

model Runtime {
id String @id @default(auto()) @map("_id") @db.ObjectId
name String @unique
type String
image RuntimeImageGroup
version String
latest Boolean
Applications Application[]
id String @id @default(auto()) @map("_id") @db.ObjectId
name String @unique
type String
image RuntimeImageGroup
version String
latest Boolean
Application Application[]
}

model Application {
Expand All @@ -79,9 +80,9 @@ model Application {
bundleName String
runtimeName String
tags String[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdBy String @db.ObjectId
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdBy String @db.ObjectId
region Region @relation(fields: [regionName], references: [name])
runtime Runtime @relation(fields: [runtimeName], references: [name])
Expand All @@ -106,14 +107,14 @@ type CloudFunctionSource {
}

model CloudFunction {
id String @id @default(auto()) @map("_id") @db.ObjectId
appid String
name String
source CloudFunctionSource
desc String
tags String[]
websocket Boolean
methods HttpMethod[]
id String @id @default(auto()) @map("_id") @db.ObjectId
appid String
name String
source CloudFunctionSource
desc String
tags String[]
websocket Boolean
methods HttpMethod[]
createdAt DateTime @default(now())
updatedAt DateTime @updatedAt
createdBy String @db.ObjectId
Expand Down
1 change: 1 addition & 0 deletions server/src/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ import { CoreModule } from './core/core.module'
import { ApplicationsModule } from './applications/applications.module'
import { AuthModule } from './auth/auth.module'
import { ThrottlerModule } from '@nestjs/throttler'
import { PrismaService } from './prisma.service'

@Module({
imports: [
Expand Down
39 changes: 20 additions & 19 deletions server/src/applications/applications.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,25 +18,28 @@ import {
ApiTags,
} from '@nestjs/swagger'
import { IRequest } from '../common/types'
import { ApplicationCoreService } from '../core/application.cr.service'
import { Application, ApplicationList } from '../core/api/application.cr'
import { JwtAuthGuard } from '../auth/jwt.auth.guard'
import { ApiResponseUtil, ResponseUtil } from '../common/response'
import { ApplicationAuthGuard } from '../auth/application.auth.guard'
import { CreateApplicationDto } from './dto/create-application.dto'
import { UpdateApplicationDto } from './dto/update-application.dto'
import { ApplicationsService } from './applications.service'
import { ApplicationCoreService } from 'src/core/application.cr.service'

@ApiTags('Application')
@Controller('applications')
@ApiBearerAuth('Authorization')
export class ApplicationsController {
constructor(private readonly appService: ApplicationCoreService) {}
constructor(
private readonly appService: ApplicationsService,
private readonly appCoreService: ApplicationCoreService,
) {}

/**
* Create application
* @returns
*/
@ApiResponseUtil(Application)
// @ApiResponseUtil(Application)
@ApiOperation({ summary: 'Create a new application' })
@UseGuards(JwtAuthGuard)
@Post()
Expand All @@ -48,8 +51,11 @@ export class ApplicationsController {
}

// create namespace
const appid = this.appService.generateAppid(6)
const namespace = await this.appService.createAppNamespace(appid, user.id)
const appid = this.appCoreService.generateAppid(6)
const namespace = await this.appCoreService.createAppNamespace(
appid,
user.id,
)
if (!namespace) {
return ResponseUtil.error('create app namespace error')
}
Expand All @@ -67,7 +73,7 @@ export class ApplicationsController {
* @param req
* @returns
*/
@ApiResponseUtil(ApplicationList)
// @ApiResponseUtil(ApplicationList)
@UseGuards(JwtAuthGuard)
@Get()
@ApiOperation({ summary: 'Get user application list' })
Expand All @@ -86,9 +92,8 @@ export class ApplicationsController {
@ApiOperation({ summary: 'Get an application by appid' })
@UseGuards(JwtAuthGuard, ApplicationAuthGuard)
@Get(':appid')
async findOne(@Param('appid') appid: string, @Req() req: IRequest) {
const user = req.user
const data = await this.appService.findOneByUser(user.id, appid)
async findOne(@Param('appid') appid: string) {
const data = await this.appService.findOne(appid)
if (null === data) {
throw new HttpException('application not found', HttpStatus.NOT_FOUND)
}
Expand All @@ -99,17 +104,15 @@ export class ApplicationsController {
/**
* Update an application
* @param dto
* @param req
* @returns
*/
@ApiOperation({ summary: 'Update an application' })
@ApiResponseUtil(Application)
// @ApiResponseUtil(Application)
@UseGuards(JwtAuthGuard, ApplicationAuthGuard)
@Patch(':appid')
async update(
@Param('appid') _appid: string,
@Param('appid') appid: string,
@Body() dto: UpdateApplicationDto,
@Req() req: IRequest,
) {
// check dto
const error = dto.validate()
Expand All @@ -118,8 +121,7 @@ export class ApplicationsController {
}

// update app
const app = req.application
const res = await this.appService.update(app, dto)
const res = await this.appService.update(appid, dto)
if (res === null) {
return ResponseUtil.error('update application error')
}
Expand All @@ -134,9 +136,8 @@ export class ApplicationsController {
@ApiOperation({ summary: 'Delete an application' })
@Delete(':appid')
@UseGuards(JwtAuthGuard, ApplicationAuthGuard)
async remove(@Param('appid') _appid: string, @Req() req: IRequest) {
const app = req.application
const res = await this.appService.remove(app)
async remove(@Param('appid') appid: string) {
const res = await this.appService.remove(appid)
if (res === null) {
return ResponseUtil.error('delete application error')
}
Expand Down
5 changes: 4 additions & 1 deletion server/src/applications/applications.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,13 @@ import { Module } from '@nestjs/common'
import { ApplicationsController } from './applications.controller'
import { SpecsController } from './specs.controller'
import { CoreModule } from '../core/core.module'
import { ApplicationsService } from './applications.service'
import { PrismaService } from '../prisma.service'

@Module({
imports: [CoreModule],
controllers: [ApplicationsController, SpecsController],
providers: [],
providers: [ApplicationsService, PrismaService],
exports: [ApplicationsService],
})
export class ApplicationsModule {}
125 changes: 125 additions & 0 deletions server/src/applications/applications.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
import { Injectable, Logger } from '@nestjs/common'
import { CreateApplicationDto } from './dto/create-application.dto'
import { Application, Prisma } from '@prisma/client'
import { PrismaService } from '../prisma.service'
import { ApplicationCoreService } from 'src/core/application.cr.service'
import { UpdateApplicationDto } from './dto/update-application.dto'
import { stringify } from 'querystring'

@Injectable()
export class ApplicationsService {
private readonly logger = new Logger(ApplicationsService.name)
constructor(
private readonly prisma: PrismaService,
private readonly applicationCore: ApplicationCoreService,
) {}

async create(userid: string, appid: string, dto: CreateApplicationDto) {
try {
const res = await this.prisma.$transaction(async (tx) => {
// create app custom object in k8s
const resource = await this.applicationCore.create(userid, appid, dto)
if (!resource) {
throw new Error('create application failed')
}

// create app in db
const data: Prisma.ApplicationCreateInput = {
name: dto.displayName,
appid,
tags: [],
createdBy: userid,
region: {
connect: {
name: dto.region,
},
},
bundle: {
connect: {
name: dto.bundleName,
},
},
runtime: {
connect: {
name: dto.runtimeName,
},
},
}

const application = await tx.application.create({
data,
})

return { application, resource }
})

return res
} catch (error) {
this.logger.error(error, error.response?.body)
return null
}
}

async findAllByUser(userid: string) {
return this.prisma.application.findMany({
where: {
createdBy: userid,
},
})
}

async findOne(appid: string) {
const application = await this.prisma.application.findUnique({
where: { appid },
})

return application
}

async update(appid: string, dto: UpdateApplicationDto) {
try {
// update app in k8s
const r = await this.applicationCore.update(appid, dto)
if (!r) {
throw new Error('update application failed')
}

// update app in db
const data: Prisma.ApplicationUpdateInput = {
updatedAt: new Date(),
}
if (dto.displayName) {
data.name = dto.displayName
}
const application = await this.prisma.application.update({
where: { appid },
data,
})

return application
} catch (error) {
this.logger.error(error, error.response?.body)
return null
}
}

async remove(appid: string) {
try {
// remove app in k8s
const r = await this.applicationCore.remove(appid)
if (!r) {
throw new Error('remove application failed')
}

// remove app in db
const application = await this.prisma.application.delete({
where: { appid },
})

return application
} catch (error) {
this.logger.error(error, error.response?.body)
return null
}
}
}
Loading

0 comments on commit d960382

Please sign in to comment.