diff --git a/src/errors.ts b/src/errors.ts index 4f7e466..5e39a76 100644 --- a/src/errors.ts +++ b/src/errors.ts @@ -27,9 +27,20 @@ export const InvalidAuthorization = () => message: 'Provided authorization credentials are invalid', }) as FastifyError; -export const QuotaExceeded = () => ({ - code: '422', - statusCode: 422, - name: 'QuotaExceeded', - message: 'Your quota has exceeded. Please delete some files to proceed.', -}); +export const QuotaExceeded = () => + ({ + code: '422', + statusCode: 422, + name: 'QuotaExceeded', + message: + 'Your quota has exceeded. Please delete some files to proceed.', + }) as FastifyError; + +export const NotFoundError = () => + ({ + code: '404', + statusCode: 404, + name: 'NotFound', + message: + 'The requested resource has never existed, deleted or has a different name or path.', + }) as FastifyError; diff --git a/src/routes/get.ts b/src/routes/get.ts new file mode 100644 index 0000000..c6b2a21 --- /dev/null +++ b/src/routes/get.ts @@ -0,0 +1,30 @@ +import { FastifyPluginAsync } from 'fastify'; +import fsp from 'node:fs/promises'; + +import { Config, config } from '../config.js'; +import { InvalidAuthorization, NotFoundError } from '../errors.js'; +import { getFilesFor, getPathFor } from '../store.js'; + +export default (async function (fastify) { + fastify.get('/get/:name', async (req, rep) => { + const key = req.headers.authorization?.replace('Bearer ', '') ?? 'none'; + + const client = Config.getClientByKey(config, key); + if (!client) { + throw InvalidAuthorization(); + } + + const files = (await getFilesFor(client.name)).map((x) => + x.replace(client.name + '-', ''), + ); + + const params = req.params as { name: string }; + + if (!files.find((x) => x === params.name)) { + throw NotFoundError(); + } + + rep.type('application/octet-stream'); + return await fsp.readFile(getPathFor(params.name, client.name)); + }); +} as FastifyPluginAsync); diff --git a/src/routes/index.ts b/src/routes/index.ts index 65cb5ae..c7602e2 100644 --- a/src/routes/index.ts +++ b/src/routes/index.ts @@ -1,8 +1,10 @@ import { FastifyPluginAsync } from 'fastify'; import upload from './upload.js'; import list from './list.js'; +import get from './get.js'; export default (async function (fastify) { await fastify.register(upload); await fastify.register(list); + await fastify.register(get); } as FastifyPluginAsync); diff --git a/src/routes/list.ts b/src/routes/list.ts index 21447e5..5cf796a 100644 --- a/src/routes/list.ts +++ b/src/routes/list.ts @@ -1,10 +1,10 @@ -import { FastifyPluginAsync } from 'fastify'; +import { type FastifyPluginAsync } from 'fastify'; import fsp from 'node:fs/promises'; import path from 'node:path'; +import { Stats } from 'node:fs'; import { Config, config } from '../config.js'; import { InvalidAuthorization } from '../errors.js'; -import { Stats } from 'node:fs'; type ListFilesResponse = { name: string;