-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpartitionByMethod.ts
More file actions
78 lines (67 loc) · 2.18 KB
/
partitionByMethod.ts
File metadata and controls
78 lines (67 loc) · 2.18 KB
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
import type {
CanonicalSpec,
HTTPMethod,
CanonicalOperation,
} from "@patchlogr/types";
import type { HashNode } from "./types/hashNode";
import type { PartitionedSpec } from "./types/partitionedSpec";
import type { HashObject } from "./types/hashObject";
import { createSHA256Hash } from "../utils/createHash";
import stableStringify from "fast-json-stable-stringify";
export function partitionByMethod(
spec: CanonicalSpec,
): PartitionedSpec<string, CanonicalOperation> {
const methodGroups = new Map<
HTTPMethod,
Array<{ key: string; operation: CanonicalOperation }>
>();
const hashObjects: HashObject<CanonicalOperation>[] = [];
Object.entries(spec.operations).forEach(([key, operation]) => {
if (!methodGroups.has(operation.method)) {
methodGroups.set(operation.method, []);
}
methodGroups.get(operation.method)?.push({
key: key,
operation,
});
});
const methodNodes: HashNode<string, CanonicalOperation>[] = [];
methodGroups.forEach((operations, method) => {
const operationLeaves: HashNode<string, CanonicalOperation>[] =
operations.map(({ key, operation }) => {
const hash = createSHA256Hash(stableStringify(operation));
hashObjects.push({ hash, data: operation });
return {
type: "leaf" as const,
key,
hash,
};
});
const methodHash = createSHA256Hash(
stableStringify(operationLeaves.map((leaf) => leaf.hash)),
);
methodNodes.push({
type: "node",
key: method,
hash: methodHash,
children: operationLeaves,
});
});
const rootHash = createSHA256Hash(
stableStringify(methodNodes.map((node) => node.hash)),
);
const root: HashNode<string, CanonicalOperation> = {
type: "node",
key: "root",
hash: rootHash,
children: methodNodes,
};
return {
root,
metadata: {
...spec.info,
...spec.security,
},
hashObjects,
};
}