summaryrefslogtreecommitdiff
path: root/u/server/filter/method.ts
blob: 6b0419dbd0f78b987ac4bd0a8c3f8b81103ef5a4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
import {
  Either,
  type ITraceable,
  LogLevel,
  PenguenoError,
  type PenguenoRequest,
  type RequestFilter,
  type ServerTrace,
  TraceUtil,
} from "@emprespresso/pengueno";

type HttpMethod =
  | "POST"
  | "GET"
  | "HEAD"
  | "PUT"
  | "DELETE"
  | "CONNECT"
  | "OPTIONS"
  | "TRACE"
  | "PATCH";

export const requireMethod = (
  methods: Array<HttpMethod>,
): RequestFilter<HttpMethod> =>
(req: ITraceable<PenguenoRequest, ServerTrace>) =>
  req.bimap(TraceUtil.withFunctionTrace(requireMethod))
    .move(Promise.resolve(req.get()))
    .map(TraceUtil.promiseify((t) => {
      const { method: _method } = t.get();
      const method = <HttpMethod> _method;
      if (!methods.includes(method)) {
        const msg = "that's not how you pet me (⋟﹏⋞)~";
        t.trace.addTrace(LogLevel.WARN).trace(msg);
        return Either.left<PenguenoError, HttpMethod>(
          new PenguenoError(msg, 405),
        );
      }
      return Either.right<PenguenoError, HttpMethod>(method);
    }))
    .get();