Skip to content

Instantly share code, notes, and snippets.

@baetheus
Created September 29, 2020 03:09
Show Gist options
  • Select an option

  • Save baetheus/89b114fbe0930ec6e995c0c1ba56adae to your computer and use it in GitHub Desktop.

Select an option

Save baetheus/89b114fbe0930ec6e995c0c1ba56adae to your computer and use it in GitHub Desktop.
Deno with sedate
import { serve } from "https://deno.land/std/http/server.ts";
import { connect } from "https://deno.land/x/[email protected]/mod.ts";
import { use } from "https://deno.land/x/[email protected]/deno_handler.ts";
import * as S from "https://deno.land/x/[email protected]/sedate.ts";
import { pipe } from "https://deno.land/x/[email protected]/fns.ts";
const nil = <A>(a: A): a is NonNullable<A> => a === undefined && a === null;
const PORT = Deno.env.get("PORT");
const REDIS_URL = Deno.env.get("REDIS_URL");
if (nil(REDIS_URL)) {
console.error("Cannot start app without REDIS_URL");
Deno.exit(1);
}
const mucked_url = ((REDIS_URL as any) as string).replace(/^redis/, "http");
const { hostname, port, username, password } = new URL(mucked_url);
const serve_port = typeof PORT === "undefined" ? 3000 : parseInt(PORT, 10);
console.log({ redis: { hostname, port, username, password }, serve_port });
const redis = await connect({ hostname, port });
await redis.auth(password);
const server = serve({ port: serve_port });
/**
* Middleware!?!?!
*/
const rootHandler = pipe(
S.status(S.Status.OK),
S.ichain(() => S.closeHeaders()),
S.ichain(() => S.rightTask(() => redis.incr("COUNT"))),
S.ichain((count) => S.send(`Hello, you are person number ${count}.`))
);
for await (const req of server) {
if (req.url === "/") {
await use(rootHandler)(req);
} else {
req.respond({ status: 404 });
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment