summaryrefslogtreecommitdiff
path: root/u/server/response.ts
blob: 453115731e31d03f3becd4935b5a61a4c1dfb9fd (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
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
import {
  type IEither,
  isEither,
  type ITraceable,
  Metric,
  type PenguenoRequest,
  type ServerTrace,
} from "@emprespresso/pengueno";

export type ResponseBody = object | string;
export type TResponseInit = ResponseInit & {
  status: number;
  headers?: Record<string, string>;
};

const getResponse = (
  req: PenguenoRequest,
  opts: TResponseInit,
): TResponseInit => {
  return {
    ...opts,
    headers: {
      ...req.baseResponseHeaders(),
      ...opts?.headers,
      "Content-Type":
        (opts?.headers?.["Content-Type"] ?? "text/plain") + "; charset=utf-8",
    },
  };
};

const ResponseCodeMetrics = [1, 2, 3, 4, 5].map((x) =>
  Metric.fromName(`response.${x}xx`),
);
export const getResponseMetric = (status: number) => {
  const index = Math.floor(status / 100) + 1;
  return ResponseCodeMetrics[index] ?? ResponseCodeMetrics[5 - 1];
};

export class PenguenoResponse extends Response {
  constructor(
    req: ITraceable<PenguenoRequest, ServerTrace>,
    msg: BodyInit,
    opts: TResponseInit,
  ) {
    const responseOpts = getResponse(req.get(), opts);
    const resMetric = getResponseMetric(opts.status);
    req.trace.trace(resMetric.count.withValue(1.0));
    responseOpts.headers;
    super(msg, responseOpts);
  }
}

export class JsonResponse extends PenguenoResponse {
  constructor(
    req: ITraceable<PenguenoRequest, ServerTrace>,
    e: BodyInit | IEither<ResponseBody, ResponseBody>,
    opts: TResponseInit,
  ) {
    const optsWithJsonContentType = {
      ...opts,
      headers: {
        ...opts?.headers,
        "Content-Type": "application/json",
      },
    };
    if (isEither<ResponseBody, ResponseBody>(e)) {
      super(
        req,
        JSON.stringify(
          e.fold(({ isLeft, value }) => (isLeft ? { error: value } : { ok: value })),
        ),
        optsWithJsonContentType,
      );
      return;
    }
    super(
      req,
      JSON.stringify(
        Math.floor(opts.status / 100) > 4 ? { error: e } : { ok: e },
      ),
      optsWithJsonContentType,
    );
  }
}