/
convertMswMatchToPact.ts
71 lines (65 loc) · 1.91 KB
/
convertMswMatchToPact.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
66
67
68
69
70
71
import { PactFile, MatchedRequest } from "./pactMswAdapter";
import { omit } from "lodash";
import { JSONValue } from "./utils/utils";
const pjson = require("../package.json");
export const readBody = async (input: Request | Response) => {
// so we don't reread body somewhere
const clone = input.clone();
if (clone.body === null) return undefined
const contentType = clone.headers.get("content-type");
if (contentType?.startsWith("application/json")) {
return clone.json() as Promise<JSONValue>;
} else if (contentType?.startsWith("multipart/form-data")) {
return clone.formData();
}
// default to text
return clone.text();
}
export const convertMswMatchToPact = async ({
consumer,
provider,
matches,
headers,
}: {
consumer: string;
provider: string;
matches: MatchedRequest[];
headers?: { excludeHeaders: string[] | undefined };
}): Promise<PactFile> => {
const pactFile: PactFile = {
consumer: { name: consumer },
provider: { name: provider },
interactions: await Promise.all(matches.map(async (match) => ({
description: match.requestId,
providerState: "",
request: {
method: match.request.method,
path: new URL(match.request.url).pathname,
headers: omit(
Object.fromEntries(match.request.headers.entries()),
headers?.excludeHeaders ?? []
),
body: await readBody(match.request),
query: new URL(match.request.url).search?.split("?")[1]
},
response: {
status: match.response.status,
headers: omit(
Object.fromEntries(match.response.headers.entries()),
headers?.excludeHeaders ?? []
),
body: await readBody(match.response),
},
}))),
metadata: {
pactSpecification: {
version: "2.0.0",
},
client: {
name: "pact-msw-adapter",
version: pjson.version,
},
},
};
return pactFile;
};