72 lines
2.0 KiB
TypeScript
72 lines
2.0 KiB
TypeScript
/* eslint-disable @typescript-eslint/no-explicit-any */
|
|
import Cors from '@fastify/cors'
|
|
import RateLimit from '@fastify/rate-limit'
|
|
import { FileStore } from '@tus/file-store'
|
|
import { Server } from '@tus/server'
|
|
|
|
import { isProduction } from '@redwoodjs/api/logger'
|
|
import { createServer } from '@redwoodjs/api-server'
|
|
|
|
import { logger } from 'src/lib/logger'
|
|
import { handleTusUpload } from 'src/lib/tus'
|
|
|
|
enum Theme {
|
|
light = 'light',
|
|
dark = 'dark',
|
|
}
|
|
|
|
;(async () => {
|
|
const { hasFlag } = await import('country-flag-icons')
|
|
|
|
if (!hasFlag(process.env.COUNTRY))
|
|
throw new Error(
|
|
'Invalid COUNTRY environment variable, please select a valid ISO-3166-1 alpha-2 country code\n See https://en.wikipedia.org/wiki/ISO_3166-1#Codes'
|
|
)
|
|
|
|
if (!(process.env.DEFAULT_THEME.toLowerCase() in Theme))
|
|
throw new Error(
|
|
'Invalid DEFAULT_THEME environment variable, please select either light or dark'
|
|
)
|
|
|
|
const server = await createServer({
|
|
logger,
|
|
configureApiServer: async (server) => {
|
|
await server.register(Cors, {
|
|
origin: isProduction
|
|
? process.env.ADDRESS_PROD
|
|
: process.env.ADDRESS_DEV,
|
|
methods: ['GET', 'POST', 'OPTIONS', 'PATCH', 'HEAD'],
|
|
credentials: isProduction ? true : false,
|
|
})
|
|
|
|
await server.register(RateLimit, {
|
|
max: Number(process.env.MAX_HTTP_CONNECTIONS_PER_MINUTE),
|
|
timeWindow: `1 minute`,
|
|
})
|
|
},
|
|
})
|
|
|
|
const tusServer = new Server({
|
|
path: '/files',
|
|
respectForwardedHeaders: true,
|
|
datastore: new FileStore({
|
|
directory: `./files_${isProduction ? 'prod' : 'dev'}`,
|
|
}),
|
|
onResponseError: (_req, res, _err) => logger.error(res),
|
|
})
|
|
|
|
server.addContentTypeParser(
|
|
'application/offset+octet-stream',
|
|
(_request, _payload, done) => done(null)
|
|
)
|
|
|
|
server.all('/files', (req, res) =>
|
|
handleTusUpload(req, res, tusServer, false)
|
|
)
|
|
server.all('/files/*', (req, res) =>
|
|
handleTusUpload(req, res, tusServer, true)
|
|
)
|
|
|
|
await server.start()
|
|
})()
|