6 Commits

30 changed files with 2939 additions and 10663 deletions

View File

@ -10,7 +10,6 @@
"rules": { "rules": {
"prettier/prettier": "error", "prettier/prettier": "error",
"import/extensions": ["error", "always"], "import/extensions": ["error", "always"],
"unicorn/prevent-abbreviations": "error", "unicorn/prevent-abbreviations": "error"
"unicorn/prefer-node-protocol": "error"
} }
} }

View File

@ -10,10 +10,10 @@ jobs:
build: build:
runs-on: 'ubuntu-latest' runs-on: 'ubuntu-latest'
steps: steps:
- uses: 'actions/checkout@v3.0.0' - uses: 'actions/checkout@v3.3.0'
- name: 'Use Node.js' - name: 'Use Node.js'
uses: 'actions/setup-node@v3.0.0' uses: 'actions/setup-node@v3.6.0'
with: with:
node-version: '16.x' node-version: '16.x'
cache: 'npm' cache: 'npm'
@ -23,3 +23,5 @@ jobs:
- name: 'Build' - name: 'Build'
run: 'npm run build' run: 'npm run build'
- run: 'npm run build:typescript'

View File

@ -10,10 +10,10 @@ jobs:
lint: lint:
runs-on: 'ubuntu-latest' runs-on: 'ubuntu-latest'
steps: steps:
- uses: 'actions/checkout@v3.0.0' - uses: 'actions/checkout@v3.3.0'
- name: 'Use Node.js' - name: 'Use Node.js'
uses: 'actions/setup-node@v3.0.0' uses: 'actions/setup-node@v3.6.0'
with: with:
node-version: '16.x' node-version: '16.x'
cache: 'npm' cache: 'npm'
@ -30,8 +30,8 @@ jobs:
- name: 'lint:markdown' - name: 'lint:markdown'
run: 'npm run lint:markdown' run: 'npm run lint:markdown'
- name: 'lint:typescript' - name: 'lint:eslint'
run: 'npm run lint:typescript' run: 'npm run lint:eslint'
- name: 'lint:prettier' - name: 'lint:prettier'
run: 'npm run lint:prettier' run: 'npm run lint:prettier'

View File

@ -8,7 +8,7 @@ jobs:
release: release:
runs-on: 'ubuntu-latest' runs-on: 'ubuntu-latest'
steps: steps:
- uses: 'actions/checkout@v3.0.0' - uses: 'actions/checkout@v3.3.0'
with: with:
fetch-depth: 0 fetch-depth: 0
persist-credentials: false persist-credentials: false
@ -21,7 +21,7 @@ jobs:
git-commit-gpgsign: true git-commit-gpgsign: true
- name: 'Use Node.js' - name: 'Use Node.js'
uses: 'actions/setup-node@v3.0.0' uses: 'actions/setup-node@v3.6.0'
with: with:
node-version: '16.x' node-version: '16.x'
cache: 'npm' cache: 'npm'
@ -32,6 +32,8 @@ jobs:
- name: 'Build' - name: 'Build'
run: 'npm run build' run: 'npm run build'
- run: 'npm run build:typescript'
- name: 'Release' - name: 'Release'
run: 'npm run release' run: 'npm run release'
env: env:

View File

@ -3,3 +3,4 @@
npm run lint:staged npm run lint:staged
npm run build npm run build
npm run build:typescript

5
.markdownlint-cli2.jsonc Normal file
View File

@ -0,0 +1,5 @@
{
"globs": ["**/*.{md,mdx}"],
"ignores": ["**/node_modules"],
"customRules": ["markdownlint-rule-relative-links"]
}

View File

@ -1,6 +1,7 @@
{ {
"default": true, "default": true,
"MD013": false, "relative-links": true,
"extends": "markdownlint/style/prettier",
"MD033": false, "MD033": false,
"MD041": false "MD041": false
} }

View File

@ -30,6 +30,7 @@
[ [
"@saithodev/semantic-release-backmerge", "@saithodev/semantic-release-backmerge",
{ {
"branches": [{ "from": "master", "to": "develop" }],
"backmergeStrategy": "merge" "backmergeStrategy": "merge"
} }
] ]

13127
package-lock.json generated

File diff suppressed because it is too large Load Diff

View File

@ -1,6 +1,6 @@
{ {
"name": "@thream/file-uploads-api", "name": "@thream/file-uploads-api",
"version": "1.0.0", "version": "1.1.1",
"description": "Thream's application programming interface to upload files.", "description": "Thream's application programming interface to upload files.",
"private": true, "private": true,
"type": "module", "type": "module",
@ -13,62 +13,66 @@
"npm": ">=8.0.0" "npm": ">=8.0.0"
}, },
"scripts": { "scripts": {
"build": "rimraf ./build && swc ./src --out-dir ./build && tsc", "build": "rimraf ./build && swc ./src --out-dir ./build",
"build:dev": "swc ./src --out-dir ./build --watch", "build:dev": "swc ./src --out-dir ./build --watch",
"build:typescript": "tsc",
"start": "node build/index.js", "start": "node build/index.js",
"dev": "concurrently -k -n \"TypeScript,Node\" -p \"[{name}]\" -c \"blue,green\" \"npm run build:dev\" \"cross-env NODE_ENV=development nodemon build/index.js\"", "dev": "concurrently -k -n \"TypeScript,Node\" -p \"[{name}]\" -c \"blue,green\" \"npm run build:dev\" \"cross-env NODE_ENV=development nodemon build/index.js\"",
"lint:commit": "commitlint", "lint:commit": "commitlint",
"lint:editorconfig": "editorconfig-checker", "lint:editorconfig": "editorconfig-checker",
"lint:markdown": "markdownlint \"**/*.md\" --dot --ignore-path \".gitignore\"", "lint:markdown": "markdownlint-cli2",
"lint:typescript": "eslint \"**/*.{js,jsx,ts,tsx}\" --ignore-path \".gitignore\"", "lint:eslint": "eslint \"**/*.{js,jsx,ts,tsx}\" --ignore-path \".gitignore\"",
"lint:prettier": "prettier \".\" --check --ignore-path \".gitignore\"", "lint:prettier": "prettier \".\" --check --ignore-path \".gitignore\"",
"lint:staged": "lint-staged", "lint:staged": "lint-staged",
"release": "semantic-release", "release": "semantic-release",
"postinstall": "husky install" "postinstall": "husky install"
}, },
"dependencies": { "dependencies": {
"@sinclair/typebox": "0.23.4", "@fastify/cors": "8.2.0",
"dotenv": "16.0.0", "@fastify/helmet": "10.1.0",
"fastify": "3.28.0", "@fastify/multipart": "7.3.0",
"fastify-cors": "6.0.3", "@fastify/rate-limit": "7.6.0",
"fastify-helmet": "7.0.1", "@fastify/sensible": "5.2.0",
"fastify-multipart": "5.3.1", "@fastify/static": "6.6.0",
"fastify-plugin": "3.0.1", "@fastify/swagger": "8.2.1",
"fastify-rate-limit": "5.8.0", "@fastify/swagger-ui": "1.3.0",
"fastify-sensible": "3.1.2", "@sinclair/typebox": "0.25.20",
"fastify-static": "4.6.1", "dotenv": "16.0.3",
"fastify-swagger": "5.1.0", "fastify": "4.11.0",
"fastify-plugin": "4.4.0",
"http-errors": "2.0.0", "http-errors": "2.0.0",
"read-pkg": "7.1.0" "read-pkg": "7.1.0"
}, },
"devDependencies": { "devDependencies": {
"@commitlint/cli": "16.2.3", "@commitlint/cli": "17.4.1",
"@commitlint/config-conventional": "16.2.1", "@commitlint/config-conventional": "17.4.0",
"@saithodev/semantic-release-backmerge": "2.1.2", "@saithodev/semantic-release-backmerge": "2.1.2",
"@semantic-release/git": "10.0.1", "@semantic-release/git": "10.0.1",
"@swc/cli": "0.1.57", "@swc/cli": "0.1.57",
"@swc/core": "1.2.164", "@swc/core": "1.3.25",
"@tsconfig/strictest": "1.0.2",
"@types/busboy": "1.5.0", "@types/busboy": "1.5.0",
"@types/http-errors": "1.8.2", "@types/http-errors": "1.8.2",
"@types/node": "17.0.23", "@types/node": "18.11.18",
"@typescript-eslint/eslint-plugin": "5.18.0", "@typescript-eslint/eslint-plugin": "5.48.1",
"concurrently": "7.1.0", "concurrently": "7.6.0",
"cross-env": "7.0.3", "cross-env": "7.0.3",
"editorconfig-checker": "4.0.2", "editorconfig-checker": "4.0.2",
"eslint": "8.12.0", "eslint": "8.31.0",
"eslint-config-conventions": "2.0.0", "eslint-config-conventions": "6.0.0",
"eslint-config-prettier": "8.5.0", "eslint-config-prettier": "8.6.0",
"eslint-plugin-import": "2.26.0", "eslint-plugin-import": "2.26.0",
"eslint-plugin-prettier": "4.0.0", "eslint-plugin-prettier": "4.2.1",
"eslint-plugin-promise": "6.0.0", "eslint-plugin-promise": "6.1.1",
"eslint-plugin-unicorn": "42.0.0", "eslint-plugin-unicorn": "45.0.2",
"husky": "7.0.4", "husky": "8.0.3",
"lint-staged": "12.3.7", "lint-staged": "13.1.0",
"markdownlint-cli": "0.31.1", "markdownlint-cli2": "0.6.0",
"nodemon": "2.0.15", "markdownlint-rule-relative-links": "1.1.1",
"prettier": "2.6.2", "nodemon": "2.0.20",
"prettier": "2.8.2",
"rimraf": "3.0.2", "rimraf": "3.0.2",
"semantic-release": "19.0.2", "semantic-release": "19.0.3",
"typescript": "4.6.3" "typescript": "4.9.4"
} }
} }

View File

@ -2,23 +2,29 @@ import { fileURLToPath } from 'node:url'
import dotenv from 'dotenv' import dotenv from 'dotenv'
import fastify from 'fastify' import fastify from 'fastify'
import fastifyCors from 'fastify-cors' import fastifyCors from '@fastify/cors'
import fastifySwagger from 'fastify-swagger' import fastifySwagger from '@fastify/swagger'
import fastifyHelmet from 'fastify-helmet' import fastifySwaggerUI from '@fastify/swagger-ui'
import fastifyRateLimit from 'fastify-rate-limit' import fastifyHelmet from '@fastify/helmet'
import fastifySensible from 'fastify-sensible' import fastifyRateLimit from '@fastify/rate-limit'
import fastifyStatic from 'fastify-static' import fastifySensible from '@fastify/sensible'
import fastifyStatic from '@fastify/static'
import { readPackage } from 'read-pkg'
import { services } from './services/index.js' import { services } from './services/index.js'
import { swaggerOptions } from './tools/configurations/swaggerOptions.js' import { UPLOADS_URL } from './tools/configurations.js'
import { UPLOADS_URL } from './tools/configurations/index.js'
dotenv.config() dotenv.config()
const packageJSON = await readPackage()
export const application = fastify({ export const application = fastify({
logger: process.env.NODE_ENV === 'development', logger: process.env['NODE_ENV'] === 'development',
ajv: { ajv: {
customOptions: { customOptions: {
format: 'full' strict: 'log',
keywords: ['kind', 'modifier'],
formats: {
full: true
}
} }
} }
}) })
@ -34,5 +40,28 @@ await application.register(fastifyStatic, {
root: fileURLToPath(UPLOADS_URL), root: fileURLToPath(UPLOADS_URL),
prefix: '/uploads/' prefix: '/uploads/'
}) })
await application.register(fastifySwagger, swaggerOptions) await application.register(fastifySwagger, {
openapi: {
info: {
title: packageJSON.name,
description: packageJSON.description,
version: packageJSON.version
},
tags: [{ name: 'users' }, { name: 'guilds' }, { name: 'messages' }],
components: {
securitySchemes: {
apiKeyAuth: {
type: 'apiKey',
name: 'X-API-KEY',
in: 'header'
}
}
}
},
hideUntagged: true
})
await application.register(fastifySwaggerUI, {
routePrefix: '/documentation',
staticCSP: true
})
await application.register(services) await application.register(services)

View File

@ -1,5 +1,8 @@
import { application } from './application.js' import { application } from './application.js'
import { HOST, PORT } from './tools/configurations/index.js' import { HOST, PORT } from './tools/configurations.js'
const address = await application.listen(PORT, HOST) const address = await application.listen({
port: PORT,
host: HOST
})
console.log('\u001B[36m%s\u001B[0m', `🚀 Server listening at ${address}`) console.log('\u001B[36m%s\u001B[0m', `🚀 Server listening at ${address}`)

View File

@ -1,4 +1,4 @@
import { FastifyPluginAsync } from 'fastify' import type { FastifyPluginAsync } from 'fastify'
import { uploadsService } from './uploads/index.js' import { uploadsService } from './uploads/index.js'

View File

@ -0,0 +1,48 @@
import type { FastifyPluginAsync, FastifySchema } from 'fastify'
import { Type } from '@sinclair/typebox'
import { fastifyErrors } from '../../../models/utils.js'
import verifyAPIKey from '../../../tools/plugins/verifyAPIKey.js'
import type { DeleteParameters } from '../../../tools/utils/deleteUploadedFile.js'
import {
deleteParameters,
deleteUploadedFile
} from '../../../tools/utils/deleteUploadedFile.js'
export const deleteServiceSchema: FastifySchema = {
tags: ['guilds'] as string[],
security: [
{
apiKeyAuth: []
}
] as Array<{ [key: string]: [] }>,
params: deleteParameters,
response: {
200: Type.String(),
400: fastifyErrors[400],
404: fastifyErrors[404],
500: fastifyErrors[500]
}
} as const
export const deleteGuildsUploadsService: FastifyPluginAsync = async (
fastify
) => {
await fastify.register(verifyAPIKey)
await fastify.route<{
Params: DeleteParameters
}>({
method: 'DELETE',
url: '/uploads/guilds/:file',
schema: deleteServiceSchema,
handler: async (request, reply) => {
return await deleteUploadedFile({
fastify,
request,
reply,
folder: 'guilds'
})
}
})
}

View File

@ -1,7 +1,8 @@
import path from 'node:path' import path from 'node:path'
import { FastifyPluginAsync, FastifySchema } from 'fastify' import type { FastifyPluginAsync, FastifySchema } from 'fastify'
import { Static, Type } from '@sinclair/typebox' import type { Static } from '@sinclair/typebox'
import { Type } from '@sinclair/typebox'
import { fastifyErrors } from '../../../models/utils.js' import { fastifyErrors } from '../../../models/utils.js'

View File

@ -1,13 +1,13 @@
import { Type } from '@sinclair/typebox' import { Type } from '@sinclair/typebox'
import { FastifyPluginAsync, FastifySchema } from 'fastify' import type { FastifyPluginAsync, FastifySchema } from 'fastify'
import fastifyMultipart from 'fastify-multipart' import fastifyMultipart from '@fastify/multipart'
import { fastifyErrors } from '../../../models/utils.js' import { fastifyErrors } from '../../../models/utils.js'
import { uploadFile } from '../../../tools/utils/uploadFile.js' import { uploadFile } from '../../../tools/utils/uploadFile.js'
import { import {
MAXIMUM_IMAGE_SIZE, MAXIMUM_IMAGE_SIZE,
SUPPORTED_IMAGE_MIMETYPE SUPPORTED_IMAGE_MIMETYPE
} from '../../../tools/configurations/index.js' } from '../../../tools/configurations.js'
import verifyAPIKey from '../../../tools/plugins/verifyAPIKey.js' import verifyAPIKey from '../../../tools/plugins/verifyAPIKey.js'
const postServiceSchema: FastifySchema = { const postServiceSchema: FastifySchema = {

View File

@ -1,19 +1,25 @@
import { FastifyPluginAsync } from 'fastify' import type { FastifyPluginAsync } from 'fastify'
import { deleteGuildsUploadsService } from './guilds/delete.js'
import { getGuildsUploadsService } from './guilds/get.js' import { getGuildsUploadsService } from './guilds/get.js'
import { postGuildsUploadsIconService } from './guilds/post.js' import { postGuildsUploadsIconService } from './guilds/post.js'
import { deleteMessagesUploadsService } from './messages/delete.js'
import { getMessagesUploadsService } from './messages/get.js' import { getMessagesUploadsService } from './messages/get.js'
import { postMessagesUploadsService } from './messages/post.js' import { postMessagesUploadsService } from './messages/post.js'
import { deleteUsersUploadsService } from './users/delete.js'
import { getUsersUploadsService } from './users/get.js' import { getUsersUploadsService } from './users/get.js'
import { postUsersUploadsLogoService } from './users/post.js' import { postUsersUploadsLogoService } from './users/post.js'
export const uploadsService: FastifyPluginAsync = async (fastify) => { export const uploadsService: FastifyPluginAsync = async (fastify) => {
await fastify.register(deleteGuildsUploadsService)
await fastify.register(getGuildsUploadsService) await fastify.register(getGuildsUploadsService)
await fastify.register(postGuildsUploadsIconService) await fastify.register(postGuildsUploadsIconService)
await fastify.register(deleteMessagesUploadsService)
await fastify.register(getMessagesUploadsService) await fastify.register(getMessagesUploadsService)
await fastify.register(postMessagesUploadsService) await fastify.register(postMessagesUploadsService)
await fastify.register(deleteUsersUploadsService)
await fastify.register(getUsersUploadsService) await fastify.register(getUsersUploadsService)
await fastify.register(postUsersUploadsLogoService) await fastify.register(postUsersUploadsLogoService)
} }

View File

@ -0,0 +1,48 @@
import type { FastifyPluginAsync, FastifySchema } from 'fastify'
import { Type } from '@sinclair/typebox'
import { fastifyErrors } from '../../../models/utils.js'
import verifyAPIKey from '../../../tools/plugins/verifyAPIKey.js'
import type { DeleteParameters } from '../../../tools/utils/deleteUploadedFile.js'
import {
deleteParameters,
deleteUploadedFile
} from '../../../tools/utils/deleteUploadedFile.js'
export const deleteServiceSchema: FastifySchema = {
tags: ['messages'] as string[],
security: [
{
apiKeyAuth: []
}
] as Array<{ [key: string]: [] }>,
params: deleteParameters,
response: {
200: Type.String(),
400: fastifyErrors[400],
404: fastifyErrors[404],
500: fastifyErrors[500]
}
} as const
export const deleteMessagesUploadsService: FastifyPluginAsync = async (
fastify
) => {
await fastify.register(verifyAPIKey)
await fastify.route<{
Params: DeleteParameters
}>({
method: 'DELETE',
url: '/uploads/messages/:file',
schema: deleteServiceSchema,
handler: async (request, reply) => {
return await deleteUploadedFile({
fastify,
request,
reply,
folder: 'messages'
})
}
})
}

View File

@ -1,7 +1,8 @@
import path from 'node:path' import path from 'node:path'
import { FastifyPluginAsync, FastifySchema } from 'fastify' import type { FastifyPluginAsync, FastifySchema } from 'fastify'
import { Static, Type } from '@sinclair/typebox' import type { Static } from '@sinclair/typebox'
import { Type } from '@sinclair/typebox'
import { fastifyErrors } from '../../../models/utils.js' import { fastifyErrors } from '../../../models/utils.js'

View File

@ -1,10 +1,10 @@
import { Type } from '@sinclair/typebox' import { Type } from '@sinclair/typebox'
import { FastifyPluginAsync, FastifySchema } from 'fastify' import type { FastifyPluginAsync, FastifySchema } from 'fastify'
import fastifyMultipart from 'fastify-multipart' import fastifyMultipart from '@fastify/multipart'
import { fastifyErrors } from '../../../models/utils.js' import { fastifyErrors } from '../../../models/utils.js'
import { uploadFile } from '../../../tools/utils/uploadFile.js' import { uploadFile } from '../../../tools/utils/uploadFile.js'
import { MAXIMUM_IMAGE_SIZE } from '../../../tools/configurations/index.js' import { MAXIMUM_IMAGE_SIZE } from '../../../tools/configurations.js'
import verifyAPIKey from '../../../tools/plugins/verifyAPIKey.js' import verifyAPIKey from '../../../tools/plugins/verifyAPIKey.js'
const postServiceSchema: FastifySchema = { const postServiceSchema: FastifySchema = {

View File

@ -0,0 +1,48 @@
import type { FastifyPluginAsync, FastifySchema } from 'fastify'
import { Type } from '@sinclair/typebox'
import { fastifyErrors } from '../../../models/utils.js'
import verifyAPIKey from '../../../tools/plugins/verifyAPIKey.js'
import type { DeleteParameters } from '../../../tools/utils/deleteUploadedFile.js'
import {
deleteParameters,
deleteUploadedFile
} from '../../../tools/utils/deleteUploadedFile.js'
export const deleteServiceSchema: FastifySchema = {
tags: ['users'] as string[],
security: [
{
apiKeyAuth: []
}
] as Array<{ [key: string]: [] }>,
params: deleteParameters,
response: {
200: Type.String(),
400: fastifyErrors[400],
404: fastifyErrors[404],
500: fastifyErrors[500]
}
} as const
export const deleteUsersUploadsService: FastifyPluginAsync = async (
fastify
) => {
await fastify.register(verifyAPIKey)
await fastify.route<{
Params: DeleteParameters
}>({
method: 'DELETE',
url: '/uploads/users/:file',
schema: deleteServiceSchema,
handler: async (request, reply) => {
return await deleteUploadedFile({
fastify,
request,
reply,
folder: 'users'
})
}
})
}

View File

@ -1,7 +1,8 @@
import path from 'node:path' import path from 'node:path'
import { FastifyPluginAsync, FastifySchema } from 'fastify' import type { FastifyPluginAsync, FastifySchema } from 'fastify'
import { Static, Type } from '@sinclair/typebox' import type { Static } from '@sinclair/typebox'
import { Type } from '@sinclair/typebox'
import { fastifyErrors } from '../../../models/utils.js' import { fastifyErrors } from '../../../models/utils.js'

View File

@ -1,13 +1,13 @@
import { Type } from '@sinclair/typebox' import { Type } from '@sinclair/typebox'
import { FastifyPluginAsync, FastifySchema } from 'fastify' import type { FastifyPluginAsync, FastifySchema } from 'fastify'
import fastifyMultipart from 'fastify-multipart' import fastifyMultipart from '@fastify/multipart'
import { fastifyErrors } from '../../../models/utils.js' import { fastifyErrors } from '../../../models/utils.js'
import { uploadFile } from '../../../tools/utils/uploadFile.js' import { uploadFile } from '../../../tools/utils/uploadFile.js'
import { import {
MAXIMUM_IMAGE_SIZE, MAXIMUM_IMAGE_SIZE,
SUPPORTED_IMAGE_MIMETYPE SUPPORTED_IMAGE_MIMETYPE
} from '../../../tools/configurations/index.js' } from '../../../tools/configurations.js'
import verifyAPIKey from '../../../tools/plugins/verifyAPIKey.js' import verifyAPIKey from '../../../tools/plugins/verifyAPIKey.js'
const postServiceSchema: FastifySchema = { const postServiceSchema: FastifySchema = {

View File

@ -4,10 +4,10 @@ import dotenv from 'dotenv'
dotenv.config() dotenv.config()
export const PORT = parseInt(process.env.PORT ?? '8000', 10) export const PORT = parseInt(process.env['PORT'] ?? '8000', 10)
export const HOST = process.env.HOST ?? '0.0.0.0' export const HOST = process.env['HOST'] ?? '0.0.0.0'
export const API_URL = process.env.API_URL ?? `http://${HOST}:${PORT}` export const API_URL = process.env['API_URL'] ?? `http://${HOST}:${PORT}`
export const API_KEY = process.env.API_KEY ?? 'apiKeySecret' export const API_KEY = process.env['API_KEY'] ?? 'apiKeySecret'
export const SRC_URL = new URL('../../', import.meta.url) export const SRC_URL = new URL('../../', import.meta.url)
export const ROOT_URL = new URL('../', SRC_URL) export const ROOT_URL = new URL('../', SRC_URL)

View File

@ -1,31 +0,0 @@
import dotenv from 'dotenv'
import { readPackage } from 'read-pkg'
import { FastifyDynamicSwaggerOptions } from 'fastify-swagger'
dotenv.config()
const packageJSON = await readPackage()
export const swaggerOptions: FastifyDynamicSwaggerOptions = {
routePrefix: '/documentation',
openapi: {
info: {
title: packageJSON.name,
description: packageJSON.description,
version: packageJSON.version
},
tags: [{ name: 'guilds' }, { name: 'messages' }, { name: 'users' }],
components: {
securitySchemes: {
apiKeyAuth: {
type: 'apiKey',
name: 'X-API-KEY',
in: 'header'
}
}
}
},
exposeRoute: true,
staticCSP: true,
hideUntagged: true
}

View File

@ -1,7 +1,7 @@
import fastifyPlugin from 'fastify-plugin' import fastifyPlugin from 'fastify-plugin'
import httpErrors from 'http-errors' import httpErrors from 'http-errors'
import { API_KEY } from '../configurations/index.js' import { API_KEY } from '../configurations.js'
const { Unauthorized, Forbidden } = httpErrors const { Unauthorized, Forbidden } = httpErrors
@ -25,5 +25,5 @@ export default fastifyPlugin(
request.apiKey = apiKey request.apiKey = apiKey
}) })
}, },
{ fastify: '3.x' } { fastify: '4.x' }
) )

View File

@ -0,0 +1,52 @@
import type { IncomingMessage, Server, ServerResponse } from 'node:http'
import { fileURLToPath } from 'node:url'
import fs from 'node:fs'
import type { Static } from '@sinclair/typebox'
import { Type } from '@sinclair/typebox'
import type {
FastifyBaseLogger,
FastifyInstance,
FastifyReply,
FastifyRequest,
FastifyTypeProviderDefault
} from 'fastify'
import { isExistingFile } from './isExistingFile.js'
export const deleteParameters = Type.Object({
file: Type.String()
})
export type DeleteParameters = Static<typeof deleteParameters>
export interface DeleteUploadedFileOptions {
folder: 'guilds' | 'messages' | 'users'
fastify: FastifyInstance<
Server<typeof IncomingMessage, typeof ServerResponse>,
IncomingMessage,
ServerResponse<IncomingMessage>,
FastifyBaseLogger,
FastifyTypeProviderDefault
>
request: FastifyRequest<{ Params: DeleteParameters }>
reply: FastifyReply
}
export const deleteUploadedFile = async (
options: DeleteUploadedFileOptions
): Promise<string> => {
const { request, fastify, reply, folder } = options
if (request.apiKey == null) {
throw fastify.httpErrors.forbidden()
}
const { file } = request.params
const fileURL = new URL(`../../../uploads/${folder}/${file}`, import.meta.url)
const filePath = fileURLToPath(fileURL)
if (!(await isExistingFile(filePath))) {
throw fastify.httpErrors.notFound('File does not exist')
}
await fs.promises.rm(filePath, { force: true })
reply.statusCode = 200
return file
}

View File

@ -0,0 +1,10 @@
import fs from 'node:fs'
export const isExistingFile = async (path: string): Promise<boolean> => {
try {
await fs.promises.access(path, fs.constants.F_OK)
return true
} catch {
return false
}
}

View File

@ -2,10 +2,10 @@ import fs from 'node:fs'
import { URL } from 'node:url' import { URL } from 'node:url'
import { randomUUID } from 'node:crypto' import { randomUUID } from 'node:crypto'
import { FastifyInstance, FastifyRequest } from 'fastify' import type { FastifyInstance, FastifyRequest } from 'fastify'
import { Multipart } from 'fastify-multipart' import type { SavedMultipartFile } from '@fastify/multipart'
import { API_URL, ROOT_URL } from '../configurations/index.js' import { API_URL, ROOT_URL } from '../configurations.js'
export interface UploadFileOptions { export interface UploadFileOptions {
folderInUploadsFolder: 'guilds' | 'messages' | 'users' folderInUploadsFolder: 'guilds' | 'messages' | 'users'
@ -33,7 +33,7 @@ export const uploadFile = async (
maximumFileSize, maximumFileSize,
supportedFileMimetype supportedFileMimetype
} = options } = options
let files: Multipart[] = [] let files: SavedMultipartFile[] = []
try { try {
files = await request.saveRequestFiles({ files = await request.saveRequestFiles({
limits: { limits: {
@ -46,10 +46,10 @@ export const uploadFile = async (
`File should be less than ${maximumFileSize}mb.` `File should be less than ${maximumFileSize}mb.`
) )
} }
if (files.length !== 1) { const file = files[0]
if (files.length !== 1 || file == null) {
throw fastify.httpErrors.badRequest('You must upload at most one file.') throw fastify.httpErrors.badRequest('You must upload at most one file.')
} }
const file = files[0]
if ( if (
supportedFileMimetype != null && supportedFileMimetype != null &&
!supportedFileMimetype.includes(file.mimetype) !supportedFileMimetype.includes(file.mimetype)
@ -60,6 +60,9 @@ export const uploadFile = async (
} }
const splitedMimetype = file.mimetype.split('/') const splitedMimetype = file.mimetype.split('/')
const fileExtension = splitedMimetype[1] const fileExtension = splitedMimetype[1]
if (fileExtension == null) {
throw fastify.httpErrors.badRequest('The file extension is not valid.')
}
const filePath = `uploads/${folderInUploadsFolder}/${randomUUID()}.${fileExtension}` const filePath = `uploads/${folderInUploadsFolder}/${randomUUID()}.${fileExtension}`
const fileURL = new URL(filePath, ROOT_URL) const fileURL = new URL(filePath, ROOT_URL)
const pathToStoreInDatabase = `${API_URL}/${filePath}` const pathToStoreInDatabase = `${API_URL}/${filePath}`

View File

@ -1,4 +1,5 @@
{ {
"extends": "@tsconfig/strictest/tsconfig.json",
"compilerOptions": { "compilerOptions": {
"target": "ESNext", "target": "ESNext",
"module": "ESNext", "module": "ESNext",
@ -7,7 +8,7 @@
"outDir": "./build", "outDir": "./build",
"rootDir": "./src", "rootDir": "./src",
"noEmit": true, "noEmit": true,
"strict": true, "exactOptionalPropertyTypes": false,
"esModuleInterop": true "checkJs": false
} }
} }