Skip to content

Commit

Permalink
feat: add scalar and openapi
Browse files Browse the repository at this point in the history
Signed-off-by: Innei <[email protected]>
  • Loading branch information
Innei committed Jul 15, 2024
1 parent 106ac29 commit ae05886
Show file tree
Hide file tree
Showing 11 changed files with 4,596 additions and 277 deletions.
11 changes: 8 additions & 3 deletions apps/core/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,7 @@
},
"dependencies": {
"@auth/drizzle-adapter": "1.4.1",
"@packages/complied": "workspace:*",
"@packages/drizzle": "workspace:*",
"@packages/utils": "workspace:*",
"@fastify/static": "7.0.4",
"@nestjs/cache-manager": "2.2.2",
"@nestjs/common": "10.3.10",
"@nestjs/config": "3.2.3",
Expand All @@ -32,10 +30,17 @@
"@nestjs/platform-fastify": "10.3.10",
"@nestjs/platform-socket.io": "10.3.10",
"@nestjs/schedule": "4.1.0",
"@nestjs/swagger": "7.4.0",
"@nestjs/throttler": "6.0.0",
"@nestjs/websockets": "10.3.10",
"@packages/complied": "workspace:*",
"@packages/drizzle": "workspace:*",
"@packages/utils": "workspace:*",
"@scalar/fastify-api-reference": "1.24.45",
"@scalar/nestjs-api-reference": "0.3.106",
"@socket.io/redis-adapter": "8.3.0",
"@socket.io/redis-emitter": "5.1.0",
"@wahyubucil/nestjs-zod-openapi": "0.1.2",
"axios": "1.7.2",
"cache-manager": "5.7.2",
"cache-manager-ioredis": "2.1.0",
Expand Down
16 changes: 14 additions & 2 deletions apps/core/src/bootstrap.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import chalk from 'chalk'
import { Logger } from 'nestjs-pretty-logger'

import { NestFactory } from '@nestjs/core'
import { patchNestjsSwagger } from '@wahyubucil/nestjs-zod-openapi' // <-- add this. Import the patch for NestJS Swagger

import { CROSS_DOMAIN, PORT } from './app.config'
import { AppModule } from './app.module'
Expand All @@ -10,7 +11,8 @@ import { SpiderGuard } from './common/guards/spider.guard'
import { LoggingInterceptor } from './common/interceptors/logging.interceptor'
import { consola, logger } from './global/consola.global'
import { isDev } from './shared/utils/environment.util'
import type { NestFastifyApplication } from '@nestjs/platform-fastify'
import { NestFastifyApplication } from '@nestjs/platform-fastify'
import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger'

// const APIVersion = 1
const Origin = CROSS_DOMAIN.allowedOrigins
Expand All @@ -35,9 +37,19 @@ export async function bootstrap() {
credentials: true,
})

isDev && app.useGlobalInterceptors(new LoggingInterceptor())
if (isDev) {
app.useGlobalInterceptors(new LoggingInterceptor())
}
app.useGlobalGuards(new SpiderGuard())

const config = new DocumentBuilder()
.setTitle('App API document')
.setVersion('1.0')
.build()
patchNestjsSwagger({ schemasSort: 'alpha' })
const document = SwaggerModule.createDocument(app, config)
SwaggerModule.setup('docs', app, document)

await app.listen(+PORT, '0.0.0.0', async () => {
app.useLogger(app.get(Logger))
consola.info('ENV:', process.env.NODE_ENV)
Expand Down
10 changes: 10 additions & 0 deletions apps/core/src/common/adapter/fastify.adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,16 @@ const app: FastifyAdapter = new FastifyAdapter({
})
export { app as fastifyApp }

app.register(require('@scalar/fastify-api-reference'), {
routePrefix: '/reference',
configuration: {
title: 'Our API Reference',
spec: {
url: '/docs-json',
},
},
})

app.getInstance().addHook('onRequest', (request, reply, done) => {
// set undefined origin
const origin = request.headers.origin
Expand Down
18 changes: 1 addition & 17 deletions apps/core/src/common/pipes/zod-validation.pipe.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1 @@
import { createZodValidationPipe } from 'nestjs-zod'
import { UnprocessableEntityException } from '@nestjs/common'
import type { ZodError } from 'zod'

export const ZodValidationPipe = createZodValidationPipe({
createValidationException: (error: ZodError) => {
const firstError = error.errors[0]
if ('expected' in firstError) {
const formatedErrorMessage: string = `Path \`${firstError.path}\` should be \`${firstError.expected}\`, but got \`${firstError.received}\``
return new UnprocessableEntityException(formatedErrorMessage)
}

return new UnprocessableEntityException(
`\`${firstError.path}\`: ${firstError.message}`,
)
},
})
export { ZodValidationPipe } from '@wahyubucil/nestjs-zod-openapi'
1 change: 1 addition & 0 deletions apps/core/src/main.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#!env node
import { name } from '../package.json'
import { register } from './global/index.global'
import '@wahyubucil/nestjs-zod-openapi/boot'

process.title = `${name} - ${process.env.NODE_ENV || 'unknown'}`
async function main() {
Expand Down
5 changes: 5 additions & 0 deletions apps/core/src/modules/user/user.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,16 @@ import { RequestContext } from '@core/common/contexts/request.context'
import { ApiController } from '@core/common/decorators/api-controller.decorator'
import { Auth } from '@core/common/decorators/auth.decorator'
import { Get } from '@nestjs/common'
import { ApiOkResponse } from '@nestjs/swagger'
import { UserSessionDto } from './user.dto'

@ApiController('users')
@Auth()
export class UserController {
@Get('/me')
@ApiOkResponse({
type: UserSessionDto,
})
async me() {
return RequestContext.currentSession().user
}
Expand Down
8 changes: 8 additions & 0 deletions apps/core/src/modules/user/user.dto.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { createZodDto } from '@wahyubucil/nestjs-zod-openapi'
import { createSelectSchema } from 'drizzle-zod'
import { users } from '@packages/drizzle/schema'

const selectUserSchema = createSelectSchema(users, {
name: (schema) => schema.name.openapi({ description: 'User name' }),
})
export class UserSessionDto extends createZodDto(selectUserSchema) {}
7 changes: 5 additions & 2 deletions apps/core/src/shared/dto/id.dto.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,11 @@
import { createZodDto } from 'nestjs-zod'
import { createZodDto } from '@wahyubucil/nestjs-zod-openapi'
import { z } from 'zod'

export class SnowflakeIdDto extends createZodDto(
z.object({
id: z.string().regex(/^\d{18}$/),
id: z
.string()
.regex(/^\d{18}$/)
.openapi({ description: 'Snowflake ID' }),
}),
) {}
2 changes: 1 addition & 1 deletion apps/core/src/shared/dto/pager.dto.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { createZodDto } from 'nestjs-zod'
import { createZodDto } from '@wahyubucil/nestjs-zod-openapi'
import { z } from 'zod'

export const basePagerSchema = z.object({
Expand Down
3 changes: 3 additions & 0 deletions biome.json
Original file line number Diff line number Diff line change
Expand Up @@ -211,6 +211,9 @@
"rules": {
"style": {
"useImportType": "off"
},
"correctness": {
"useHookAtTopLevel": "off"
}
}
}
Expand Down
Loading

0 comments on commit ae05886

Please sign in to comment.