This repository has been archived by the owner on Mar 24, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.ts
65 lines (49 loc) · 1.49 KB
/
util.ts
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
// Copyright 2023-latest the httpland authors. All rights reserved. MIT license.
// This module is browser compatible.
import { ascend, isNegativeNumber, isNull, Method } from "./deps.ts";
import type { Precondition } from "./types.ts";
export function isNotSelectionOrModificationMethod(method: string): boolean {
return ([Method.Connect, Method.Options, Method.Trace] as string[]).includes(
method,
);
}
enum PreconditionPriority {
"if-match",
"if-none-match",
"if-modified-since",
"if-unmodified-since",
}
export type Ord = 1 | 0 | -1;
export function toPriority(input: string): number {
input = input.toLowerCase();
const Order = Object.values(PreconditionPriority);
const result = Order.indexOf(input);
return isNegativeNumber(result) ? Infinity : result;
}
export function ascendPrecondition(
left: Precondition,
right: Precondition,
): Ord {
return ascendPreconditionHeader(left.header, right.header);
}
export function ascendPreconditionHeader(
left: string,
right: string,
): Ord {
const l = toPriority(left);
const r = toPriority(right);
return ascend(l, r);
}
export async function applyPrecondition(
request: Request,
response: Response,
precondition: Precondition,
): Promise<Response | void> {
const fieldValue = request.headers.get(precondition.header);
if (isNull(fieldValue)) return;
const evalResult = await precondition.evaluate(request, response, {
fieldValue,
});
if (evalResult) return;
return precondition.respond(request);
}