Key/value storage, local or remote
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
storage/src/server.ts

56 lines
1.5 KiB

import { KeyValueStorage } from "./basic.ts";
import { Application, oakCors, readAll } from "../deps.server.ts";
import { HEADER_REPLYIER, HEADER_REQUESTER } from "./remote.ts";
type Server = {
close: () => Promise<void>;
};
/**
* Start a server compliant with RestRemoteStorage
*/
export function startRestServer(
port: number,
storage: KeyValueStorage,
): Server {
const app = new Application();
const controller = new AbortController();
app.use(oakCors());
app.use(async (context) => {
if (context.request.headers.get(HEADER_REQUESTER)) {
context.response.headers.set(HEADER_REPLYIER, "ok");
const method = context.request.method;
const path = context.request.url.pathname;
if (method == "GET") {
const result = await storage.get(path);
if (result === null) {
context.response.status = 404;
} else {
context.response.body = result;
}
} else if (method == "PUT") {
const body = context.request.body({ type: "reader" });
const data = await readAll(body.value);
const value = new TextDecoder().decode(data);
await storage.set(path, value);
} else if (method == "DELETE") {
await storage.set(path, null);
} else {
context.response.status = 405;
}
} else {
context.response.status = 400;
}
});
const listen = app.listen({ port, signal: controller.signal });
return {
close: async () => {
controller.abort();
await listen;
},
};
}