Skip to content

Commit

Permalink
feat(plugin): add @fastify/static
Browse files Browse the repository at this point in the history
  • Loading branch information
jlenon7 committed Feb 25, 2024
1 parent 3a1d547 commit e31f26a
Show file tree
Hide file tree
Showing 9 changed files with 258 additions and 52 deletions.
21 changes: 11 additions & 10 deletions package-lock.json

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

7 changes: 4 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@athenna/http",
"version": "4.22.0",
"version": "4.23.0",
"description": "The Athenna Http server. Built on top of fastify.",
"license": "MIT",
"author": "João Lenon <lenon@athenna.io>",
Expand Down Expand Up @@ -72,17 +72,18 @@
"#tests": "./tests/index.js"
},
"devDependencies": {
"@athenna/artisan": "^4.35.0",
"@athenna/artisan": "^4.37.0",
"@athenna/common": "^4.34.0",
"@athenna/config": "^4.16.0",
"@athenna/ioc": "^4.16.0",
"@athenna/logger": "^4.17.0",
"@athenna/test": "^4.22.0",
"@athenna/tsconfig": "^4.12.0",
"@athenna/view": "^4.14.0",
"@athenna/view": "^4.18.0",
"@fastify/cors": "^8.4.2",
"@fastify/helmet": "^11.1.1",
"@fastify/rate-limit": "^8.1.1",
"@fastify/static": "^7.0.1",
"@fastify/swagger": "^8.12.2",
"@fastify/swagger-ui": "^3.0.0",
"@typescript-eslint/eslint-plugin": "^6.7.4",
Expand Down
78 changes: 75 additions & 3 deletions src/context/Response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@
* file that was distributed with this source code.
*/

import { View } from '@athenna/view'
import type { FastifyReply } from 'fastify'
import type { SendOptions } from '@fastify/static'
import type { Request } from '#src/context/Request'
import type { FastifyHelmetOptions } from '@fastify/helmet'

export class Response {
Expand All @@ -16,8 +19,14 @@ export class Response {
*/
public response: FastifyReply

public constructor(response: FastifyReply) {
/**
* The request object from request context.
*/
public request: Request

public constructor(response: FastifyReply, request?: Request) {
this.response = response
this.request = request
}

/**
Expand Down Expand Up @@ -52,7 +61,23 @@ export class Response {
* Get the time in MS of how much the request has taken to response.
*/
public get responseTime(): number {
return this.response.getResponseTime()
return this.response.elapsedTime
}

/**
* Terminated the request sending a view to be rendered.
*/
public async view(view: string, data?: any): Promise<Response> {
const content = await View.render(view, { ...data, request: this.request })

await this.safeHeader(
'Content-Type',
'text/html; charset=utf-8'
).response.send(content)

this.response.body = content

return this
}

/**
Expand All @@ -66,6 +91,53 @@ export class Response {
return this
}

public sendFile(filename: string, filepath?: string): Promise<Response>
public sendFile(
filename: string,
options?: string | SendOptions
): Promise<Response>

public sendFile(
filename: string,
filepath?: string,
options?: SendOptions
): Promise<Response>

/**
* Terminated the request sending a file.
*/
public async sendFile(
filename: string,
filepath?: string,
options?: SendOptions
): Promise<Response> {
await this.response.sendFile(filename, filepath, options)

return this
}

public download(filepath: string, filename?: string): Promise<Response>
public download(
filepath: string,
options?: string | SendOptions
): Promise<Response>

public download(
filename: string,
filepath?: string,
options?: SendOptions
): Promise<Response>

public async download(
filepath: string,
filename?: string,
options?: SendOptions
): Promise<Response> {
await this.response.download(filename, filepath, options)

return this
}

/**
* Set the response status code.
*/
Expand All @@ -92,7 +164,7 @@ export class Response {
}

/**
* Add some header safelly to the response. This means that the header is not
* Add some header safely to the response. This means that the header is not
* going to be added if is already set.
*/
public safeHeader(header: string, value: any): Response {
Expand Down
29 changes: 22 additions & 7 deletions src/handlers/FastifyHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,12 @@
* file that was distributed with this source code.
*/

import type { InterceptHandler, TerminateHandler } from '#src/types'

import { Is } from '@athenna/common'
import { Request } from '#src/context/Request'
import { Response } from '#src/context/Response'
import type { RequestHandler } from '#src/types/contexts/Context'
import type { ErrorHandler } from '#src/types/contexts/ErrorContext'
import type { InterceptHandler, TerminateHandler } from '#src/types'
import type { FastifyReply, FastifyRequest, RouteHandlerMethod } from 'fastify'

export class FastifyHandler {
Expand All @@ -24,12 +23,13 @@ export class FastifyHandler {
public static request(handler: RequestHandler): RouteHandlerMethod {
return async (req: FastifyRequest, res: FastifyReply) => {
const request = new Request(req)
const response = new Response(res)

if (!req.data) {
req.data = {}
}

const response = new Response(res, request)

await handler({
request,
response,
Expand All @@ -55,7 +55,12 @@ export class FastifyHandler {
public static intercept(handler: InterceptHandler) {
return async (req: FastifyRequest, res: FastifyReply, payload: any) => {
const request = new Request(req)
const response = new Response(res)

if (!req.data) {
req.data = {}
}

const response = new Response(res, request)

if (Is.Json(payload)) {
payload = JSON.parse(payload)
Expand Down Expand Up @@ -90,7 +95,12 @@ export class FastifyHandler {
public static terminate(handler: TerminateHandler) {
return async (req: FastifyRequest, res: FastifyReply) => {
const request = new Request(req)
const response = new Response(res)

if (!req.data) {
req.data = {}
}

const response = new Response(res, request)

await handler({
request,
Expand All @@ -101,7 +111,7 @@ export class FastifyHandler {
body: res.body || req.body,
headers: res.getHeaders(),
status: res.statusCode,
responseTime: res.getResponseTime()
responseTime: res.elapsedTime
})
}
}
Expand All @@ -112,7 +122,12 @@ export class FastifyHandler {
public static error(handler: ErrorHandler) {
return async (error: any, req: FastifyRequest, res: FastifyReply) => {
const request = new Request(req)
const response = new Response(res)

if (!req.data) {
req.data = {}
}

const response = new Response(res, request)

await handler({
request,
Expand Down
24 changes: 24 additions & 0 deletions src/kernels/HttpKernel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ const helmetPlugin = await Module.safeImport('@fastify/helmet')
const swaggerPlugin = await Module.safeImport('@fastify/swagger')
const swaggerUiPlugin = await Module.safeImport('@fastify/swagger-ui')
const rateLimitPlugin = await Module.safeImport('@fastify/rate-limit')
const staticPlugin = await Module.safeImport('@fastify/static')
const rTracerPlugin = await Module.safeImport('cls-rtracer')

export class HttpKernel {
Expand Down Expand Up @@ -146,6 +147,29 @@ export class HttpKernel {
await Server.plugin(rateLimitPlugin, this.getConfig('http.rateLimit'))
}

/**
* Register the @fastify/static plugin in the Http server.
*/
public async registerStatic(): Promise<void> {
if (Config.is('http.static.enabled', false)) {
debug(
'Not able to register static plugin. Set the http.static.enabled configuration as true.'
)

return
}

if (!staticPlugin) {
debug(
'Not able to register static plugin. Install @fastify/static package.'
)

return
}

await Server.plugin(staticPlugin, this.getConfig('http.static'))
}

/**
* Register the cls-rtracer plugin in the Http server.
*/
Expand Down
5 changes: 5 additions & 0 deletions tests/fixtures/config/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ export default {
continueExceeding: false,
enableDraftSpec: false
},
static: {
enabled: true,
root: Path.fixtures('config'),
prefix: '/static'
},
rTracer: {
echoHeader: false,
useHeader: false,
Expand Down
29 changes: 0 additions & 29 deletions tests/fixtures/config/view.ts

This file was deleted.

Loading

0 comments on commit e31f26a

Please sign in to comment.