Files
3dverse-testtask/src/restapi.ts
T

65 lines
2.2 KiB
TypeScript

import { Context, Router } from "https://deno.land/x/oak/mod.ts";
import { FileService } from "./fileservice.ts";
import { readerFromStreamReader, readableStreamFromReader, TextLineStream } from "https://deno.land/std@0.191.0/streams/mod.ts";
import { asyncIterableToArray } from "./utils.ts";
type Handler = (ctx: Context) => void;
function listFileHandlerFactory(fileService: FileService): Handler {
return async (ctx: Context) => {
ctx.response.type = "application/json";
ctx.response.body = await asyncIterableToArray(fileService.list());
};
}
function createFileHandlerFactory(fileService: FileService): Handler {
return async (ctx: Context) => {
const untypedCtx: any = ctx;
ctx.response.body = 'This is a post';
const path = untypedCtx.request.url.searchParams.get('path');
const reqBody = await ctx.request.body({ type: "stream" }).value;
const reader = readerFromStreamReader(reqBody.getReader())
await fileService.createFromReader(path, reader);
};
}
function getFileHandlerFactory(fileService: FileService): Handler {
return async (ctx: Context) => {
const untypedCtx: any = ctx;
const fileId = untypedCtx.params.path;
const reader = await fileService.getContentAsReader(fileId);
if(reader == null){
ctx.response.status = 404;
return;
}
ctx.response.status = 200;
ctx.response.body = reader;
};
}
function deleteFileHandlerFactory(fileService: FileService): Handler {
return async (ctx: Context) => {
const untypedCtx: any = ctx;
const path = untypedCtx.params.path;
const isDeleted = await fileService.deleteByPath(path);
if(!isDeleted){
ctx.response.status = 404;
return;
}
ctx.response.status = 200;
};
}
export function buildAPI(router: Router, fileService: FileService): Router {
router.get('/files', listFileHandlerFactory(fileService));
router.get('/files/:path', getFileHandlerFactory(fileService));
router.delete('/file/:path', deleteFileHandlerFactory(fileService));
router.post('/files', createFileHandlerFactory(fileService));
return router;
}