storage/server.ts
2021-06-22 16:10:17 +02:00

71 lines
1.7 KiB
TypeScript
Executable file

#!/usr/bin/env -S deno run --allow-read --allow-net
import { getLocalStorage } from "./mod.ts";
import { KeyValueStorage } from "./basic.ts";
import { HEADER_REPLYIER, HEADER_REQUESTER } from "./remote.ts";
import { json, opine, opineCors, readAll } from "./deps.ts";
const PORT = 5001;
type Server = {
close: () => Promise<void>;
};
/**
* Start a server compliant with RestRemoteStorage
*/
export function startRestServer(
port: number,
storage: KeyValueStorage,
): Promise<Server> {
const app = opine();
app.use(
opineCors({ exposedHeaders: [HEADER_REPLYIER] }),
json(),
(req, res, next) => {
if (req.get(HEADER_REQUESTER)) {
res.set(HEADER_REPLYIER, "ok");
next();
} else {
res.setStatus(400).send();
}
},
);
app.get("*", (req, res, next) => {
storage.get(req.path).then((result) => {
if (result === null) {
res.setStatus(404).send();
} else {
res.send(result);
}
}).catch(next);
});
app.put("*", (req, res, next) => {
readAll(req.body).then((body) => {
const value = new TextDecoder().decode(body);
storage.set(req.path, value).then(() => {
res.send();
}).catch(next);
}).catch(next);
});
app.delete("*", (req, res, next) => {
storage.set(req.path, null).then(() => {
res.send();
}).catch(next);
});
return new Promise((resolve) => {
const server = app.listen(port, () => {
resolve({
close: () =>
new Promise((resolve, reject) => {
server.close();
}),
});
});
});
}
if (import.meta.main) {
await startRestServer(PORT, getLocalStorage("tk-storage-server"));
console.log(`Server running, use http://localhost:${PORT} to connect`);
}