70 lines
1.7 KiB
TypeScript
Executable file
70 lines
1.7 KiB
TypeScript
Executable file
#!./run
|
|
import { KeyValueStorage } from "./basic.ts";
|
|
import { json, opine, opineCors, readAll } from "./deps.ts";
|
|
import { getLocalStorage } from "./mod.ts";
|
|
import { HEADER_REPLYIER, HEADER_REQUESTER } from "./remote.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: async () => {
|
|
server.close();
|
|
},
|
|
});
|
|
});
|
|
});
|
|
}
|
|
|
|
if (import.meta.main) {
|
|
await startRestServer(PORT, getLocalStorage("tk-storage-server"));
|
|
console.log(`Server running, use http://localhost:${PORT} to connect`);
|
|
}
|