@bifravst/http-api-mock 2.1.354 → 2.1.356
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/npm/mock.js +27 -0
- package/npm/parseMockRequest.js +17 -0
- package/{dist/src → npm}/parseMockResponse.js +8 -10
- package/npm/randomString.js +2 -0
- package/{dist/src → npm}/requests.d.ts +1 -1
- package/npm/requests.js +11 -0
- package/{dist/src → npm}/responses.js +6 -6
- package/{dist/src → npm}/sortQueryString.d.ts +1 -1
- package/{dist/src → npm}/sortQueryString.js +11 -10
- package/package.json +23 -27
- package/cdk/App.ts +0 -26
- package/cdk/Stack.ts +0 -66
- package/cdk/http-api-mock.ts +0 -41
- package/cdk/resources/HttpApiMock.ts +0 -119
- package/cdk/resources/checkMatchingQueryParams.spec.ts +0 -67
- package/cdk/resources/checkMatchingQueryParams.ts +0 -40
- package/cdk/resources/http-api-mock-lambda.ts +0 -147
- package/cdk/resources/splitMockResponse.spec.ts +0 -17
- package/cdk/resources/splitMockResponse.ts +0 -25
- package/cli.js +0 -5
- package/dist/cdk/App.d.ts +0 -11
- package/dist/cdk/App.js +0 -12
- package/dist/cdk/Stack.d.ts +0 -20
- package/dist/cdk/Stack.js +0 -40
- package/dist/cdk/http-api-mock.d.ts +0 -1
- package/dist/cdk/http-api-mock.js +0 -35
- package/dist/cdk/resources/HttpApiMock.d.ts +0 -14
- package/dist/cdk/resources/HttpApiMock.js +0 -87
- package/dist/cdk/resources/checkMatchingQueryParams.d.ts +0 -5
- package/dist/cdk/resources/checkMatchingQueryParams.js +0 -33
- package/dist/cdk/resources/checkMatchingQueryParams.spec.d.ts +0 -1
- package/dist/cdk/resources/checkMatchingQueryParams.spec.js +0 -57
- package/dist/cdk/resources/http-api-mock-lambda.d.ts +0 -2
- package/dist/cdk/resources/http-api-mock-lambda.js +0 -98
- package/dist/cdk/resources/splitMockResponse.d.ts +0 -4
- package/dist/cdk/resources/splitMockResponse.js +0 -20
- package/dist/cdk/resources/splitMockResponse.spec.d.ts +0 -1
- package/dist/cdk/resources/splitMockResponse.spec.js +0 -13
- package/dist/src/cli.d.ts +0 -1
- package/dist/src/cli.js +0 -88
- package/dist/src/mock.js +0 -31
- package/dist/src/mock.spec.js +0 -36
- package/dist/src/parseMockRequest.js +0 -19
- package/dist/src/parseMockRequest.spec.js +0 -23
- package/dist/src/parseMockResponse.spec.js +0 -20
- package/dist/src/randomString.js +0 -5
- package/dist/src/requests.js +0 -11
- package/dist/src/sortQueryString.spec.js +0 -18
- package/src/cli.ts +0 -109
- package/src/mock.spec.ts +0 -52
- package/src/mock.ts +0 -61
- package/src/parseMockRequest.spec.ts +0 -30
- package/src/parseMockRequest.ts +0 -35
- package/src/parseMockResponse.spec.ts +0 -27
- package/src/parseMockResponse.ts +0 -35
- package/src/randomString.ts +0 -7
- package/src/requests.ts +0 -28
- package/src/responses.ts +0 -50
- package/src/sortQueryString.spec.ts +0 -38
- package/src/sortQueryString.ts +0 -26
- /package/{dist/src → npm}/mock.d.ts +0 -0
- /package/{dist/src → npm}/mock.spec.d.ts +0 -0
- /package/{dist/src → npm}/parseMockRequest.d.ts +0 -0
- /package/{dist/src → npm}/parseMockRequest.spec.d.ts +0 -0
- /package/{dist/src → npm}/parseMockResponse.d.ts +0 -0
- /package/{dist/src → npm}/parseMockResponse.spec.d.ts +0 -0
- /package/{dist/src → npm}/randomString.d.ts +0 -0
- /package/{dist/src → npm}/responses.d.ts +0 -0
- /package/{dist/src → npm}/sortQueryString.spec.d.ts +0 -0
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
import assert from 'node:assert';
|
|
2
|
-
import { describe, it } from 'node:test';
|
|
3
|
-
import { splitMockResponse } from './splitMockResponse.js';
|
|
4
|
-
void describe('split mock response', () => {
|
|
5
|
-
void it('should parse headers and body', () => assert.deepEqual(splitMockResponse(`Content-Type: application/octet-stream
|
|
6
|
-
|
|
7
|
-
(binary A-GNSS data) other types`), {
|
|
8
|
-
headers: {
|
|
9
|
-
'Content-Type': 'application/octet-stream',
|
|
10
|
-
},
|
|
11
|
-
body: '(binary A-GNSS data) other types',
|
|
12
|
-
}));
|
|
13
|
-
});
|
package/dist/src/cli.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export declare const cli: () => Promise<void>;
|
package/dist/src/cli.js
DELETED
|
@@ -1,88 +0,0 @@
|
|
|
1
|
-
import { CloudFormationClient } from '@aws-sdk/client-cloudformation';
|
|
2
|
-
import { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts';
|
|
3
|
-
import { stackOutput } from '@bifravst/cloudformation-helpers';
|
|
4
|
-
import run from '@bifravst/run';
|
|
5
|
-
import chalk from 'chalk';
|
|
6
|
-
import path, { dirname } from 'node:path';
|
|
7
|
-
import { fileURLToPath } from 'node:url';
|
|
8
|
-
import { randomString } from './randomString.js';
|
|
9
|
-
const die = (err) => {
|
|
10
|
-
console.error('');
|
|
11
|
-
console.error(chalk.yellow('⚠️'), chalk.red.bold(err.message));
|
|
12
|
-
console.error('');
|
|
13
|
-
console.error(err);
|
|
14
|
-
process.exit(1);
|
|
15
|
-
};
|
|
16
|
-
process.on('uncaughtException', die);
|
|
17
|
-
process.on('unhandledRejection', die);
|
|
18
|
-
const cdkApp = () => [
|
|
19
|
-
'--app',
|
|
20
|
-
`"npx tsx --no-warnings ${path.join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'cdk', 'http-api-mock.ts')}"`,
|
|
21
|
-
];
|
|
22
|
-
export const cli = async () => {
|
|
23
|
-
await whoAmI();
|
|
24
|
-
if (process.argv.includes('destroy')) {
|
|
25
|
-
await destroy(getStackNameFromArgs('destroy'));
|
|
26
|
-
return;
|
|
27
|
-
}
|
|
28
|
-
if (process.argv.includes('describe')) {
|
|
29
|
-
await describe(getStackNameFromArgs('describe'));
|
|
30
|
-
return;
|
|
31
|
-
}
|
|
32
|
-
const stackName = `http-api-mock-${randomString()}`;
|
|
33
|
-
console.error(chalk.yellow(`Stack name`), chalk.green(stackName));
|
|
34
|
-
await run({
|
|
35
|
-
command: 'npx',
|
|
36
|
-
args: ['cdk', ...cdkApp(), 'deploy', '--require-approval', 'never'],
|
|
37
|
-
env: {
|
|
38
|
-
...process.env,
|
|
39
|
-
HTTP_API_MOCK_STACK_NAME: stackName,
|
|
40
|
-
},
|
|
41
|
-
log: {
|
|
42
|
-
debug: (msg) => console.error(chalk.blueBright('[CDK]'), chalk.blue(msg)),
|
|
43
|
-
},
|
|
44
|
-
});
|
|
45
|
-
await describe(stackName);
|
|
46
|
-
};
|
|
47
|
-
const whoAmI = async () => {
|
|
48
|
-
try {
|
|
49
|
-
const me = await new STSClient({}).send(new GetCallerIdentityCommand({}));
|
|
50
|
-
if (me.Account === undefined)
|
|
51
|
-
throw new Error(`Not authenticated!`);
|
|
52
|
-
console.error(chalk.yellow('Account'), chalk.green(me.Account));
|
|
53
|
-
return {
|
|
54
|
-
Account: me.Account,
|
|
55
|
-
};
|
|
56
|
-
}
|
|
57
|
-
catch (err) {
|
|
58
|
-
throw new Error(`Not authenticated!`);
|
|
59
|
-
}
|
|
60
|
-
};
|
|
61
|
-
const destroy = async (stackName) => {
|
|
62
|
-
console.error(chalk.yellow(`Stack name`), chalk.green(stackName));
|
|
63
|
-
await run({
|
|
64
|
-
command: 'npx',
|
|
65
|
-
args: ['cdk', ...cdkApp(), 'destroy', '-f'],
|
|
66
|
-
env: {
|
|
67
|
-
...process.env,
|
|
68
|
-
HTTP_API_MOCK_STACK_NAME: stackName,
|
|
69
|
-
},
|
|
70
|
-
log: {
|
|
71
|
-
debug: (msg) => console.error(chalk.blueBright('[CDK]'), chalk.blue(msg)),
|
|
72
|
-
},
|
|
73
|
-
});
|
|
74
|
-
console.error(chalk.green(`Stack destroyed`));
|
|
75
|
-
};
|
|
76
|
-
const describe = async (stackName) => {
|
|
77
|
-
console.log(JSON.stringify({
|
|
78
|
-
stackName,
|
|
79
|
-
...(await stackOutput(new CloudFormationClient({}))(stackName)),
|
|
80
|
-
}, null, 2));
|
|
81
|
-
};
|
|
82
|
-
const getStackNameFromArgs = (command) => {
|
|
83
|
-
const stackName = process.argv[process.argv.indexOf(command) + 1];
|
|
84
|
-
if (stackName === undefined) {
|
|
85
|
-
throw new Error(`Must provide a stack name!`);
|
|
86
|
-
}
|
|
87
|
-
return stackName;
|
|
88
|
-
};
|
package/dist/src/mock.js
DELETED
|
@@ -1,31 +0,0 @@
|
|
|
1
|
-
import { registerResponse } from './responses.js';
|
|
2
|
-
export const mockResponse = (db, responsesTable) => async (methodPathQuery, response, keep) => {
|
|
3
|
-
const [method, pathWithQuery] = methodPathQuery.split(' ', 2);
|
|
4
|
-
if (!/^[A-Z]+$/.test(method ?? ''))
|
|
5
|
-
throw new Error(`Invalid method ${method} in ${methodPathQuery}!`);
|
|
6
|
-
if (pathWithQuery === undefined)
|
|
7
|
-
throw new Error(`Missing path in ${methodPathQuery}!`);
|
|
8
|
-
const [path, query] = pathWithQuery.split('?', 2);
|
|
9
|
-
if (path.startsWith('/'))
|
|
10
|
-
throw new Error(`Path ${path} must not start with /!`);
|
|
11
|
-
const bodyParts = [];
|
|
12
|
-
if (response.headers !== undefined) {
|
|
13
|
-
for (const [k, v] of response.headers.entries()) {
|
|
14
|
-
bodyParts.push(`${k}: ${v}`);
|
|
15
|
-
}
|
|
16
|
-
bodyParts.push('');
|
|
17
|
-
}
|
|
18
|
-
if (response.body !== undefined)
|
|
19
|
-
bodyParts.push(response.body);
|
|
20
|
-
await registerResponse(db, responsesTable, {
|
|
21
|
-
path,
|
|
22
|
-
method: method ?? 'GET',
|
|
23
|
-
queryParams: new URLSearchParams(query),
|
|
24
|
-
body: bodyParts.length > 0 ? bodyParts.join('\n') : undefined,
|
|
25
|
-
statusCode: response.status,
|
|
26
|
-
keep,
|
|
27
|
-
});
|
|
28
|
-
};
|
|
29
|
-
export const mock = ({ db, responsesTable, }) => ({
|
|
30
|
-
response: mockResponse(db, responsesTable),
|
|
31
|
-
});
|
package/dist/src/mock.spec.js
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
import { unmarshall } from '@aws-sdk/util-dynamodb';
|
|
2
|
-
import assert from 'node:assert/strict';
|
|
3
|
-
import { describe, it, mock as testMock } from 'node:test';
|
|
4
|
-
import { mock } from './mock.js';
|
|
5
|
-
void describe('mock()', () => {
|
|
6
|
-
void it('should register a response', async () => {
|
|
7
|
-
const db = {
|
|
8
|
-
send: testMock.fn(async () => Promise.resolve(undefined)),
|
|
9
|
-
};
|
|
10
|
-
const httpApiMock = mock({
|
|
11
|
-
db: db,
|
|
12
|
-
responsesTable: 'response-table',
|
|
13
|
-
});
|
|
14
|
-
await httpApiMock.response(`GET foo/bar?k=v`, {
|
|
15
|
-
status: 200,
|
|
16
|
-
headers: new Headers({
|
|
17
|
-
'content-type': 'application/json; charset=utf-8',
|
|
18
|
-
}),
|
|
19
|
-
body: JSON.stringify({
|
|
20
|
-
result: 'some-value',
|
|
21
|
-
}),
|
|
22
|
-
});
|
|
23
|
-
assert.equal(db.send.mock.callCount(), 1);
|
|
24
|
-
const [{ input: args }] = db.send.mock.calls[0]?.arguments;
|
|
25
|
-
assert.equal(args.TableName, 'response-table');
|
|
26
|
-
const { methodPathQuery, statusCode, body, queryParams } = unmarshall(args.Item);
|
|
27
|
-
assert.equal(statusCode, 200);
|
|
28
|
-
assert.equal(methodPathQuery, 'GET foo/bar?k=v');
|
|
29
|
-
assert.equal(body, [
|
|
30
|
-
`content-type: application/json; charset=utf-8`,
|
|
31
|
-
``,
|
|
32
|
-
JSON.stringify({ result: 'some-value' }),
|
|
33
|
-
].join('\n'));
|
|
34
|
-
assert.deepEqual(queryParams, { k: 'v' });
|
|
35
|
-
});
|
|
36
|
-
});
|
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
export const parseMockRequest = (r) => {
|
|
2
|
-
const lines = r.split('\n');
|
|
3
|
-
const methodResourceProtol = lines.shift();
|
|
4
|
-
const blankLineLocation = lines.indexOf('');
|
|
5
|
-
const headerLines = blankLineLocation === -1 ? lines : lines.slice(0, blankLineLocation);
|
|
6
|
-
const body = blankLineLocation === -1
|
|
7
|
-
? ''
|
|
8
|
-
: lines.slice(blankLineLocation + 1).join('\n');
|
|
9
|
-
const requestInfo = /^(?<method>[A-Z]+) (?<resource>[^ ]+) (?<protocol>HTTP\/[0-9.]+)/.exec(methodResourceProtol ?? '')?.groups;
|
|
10
|
-
if (requestInfo === null)
|
|
11
|
-
throw new Error(`Invalid request info: ${methodResourceProtol}`);
|
|
12
|
-
return {
|
|
13
|
-
...requestInfo,
|
|
14
|
-
headers: headerLines
|
|
15
|
-
.map((s) => s.split(':', 2))
|
|
16
|
-
.reduce((headers, [k, v]) => ({ ...headers, [k ?? '']: v?.trim() }), {}),
|
|
17
|
-
body,
|
|
18
|
-
};
|
|
19
|
-
};
|
|
@@ -1,23 +0,0 @@
|
|
|
1
|
-
import assert from 'node:assert/strict';
|
|
2
|
-
import { describe, it } from 'node:test';
|
|
3
|
-
import { parseMockRequest } from './parseMockRequest.js';
|
|
4
|
-
void describe('parseMockRequest()', () => {
|
|
5
|
-
void it('should parse method, resource, protocol, headers and body', () => assert.deepEqual(parseMockRequest([
|
|
6
|
-
`PATCH /v1/devices/foo/state HTTP/1.1`,
|
|
7
|
-
`Content-Length: 36`,
|
|
8
|
-
`Content-Type: application/json`,
|
|
9
|
-
`If-Match: 8835`,
|
|
10
|
-
``,
|
|
11
|
-
`{"desired":{"config":{"nod":null}}}`,
|
|
12
|
-
].join('\n')), {
|
|
13
|
-
method: 'PATCH',
|
|
14
|
-
resource: '/v1/devices/foo/state',
|
|
15
|
-
protocol: 'HTTP/1.1',
|
|
16
|
-
headers: {
|
|
17
|
-
'Content-Length': '36',
|
|
18
|
-
'Content-Type': 'application/json',
|
|
19
|
-
'If-Match': '8835',
|
|
20
|
-
},
|
|
21
|
-
body: '{"desired":{"config":{"nod":null}}}',
|
|
22
|
-
}));
|
|
23
|
-
});
|
|
@@ -1,20 +0,0 @@
|
|
|
1
|
-
import assert from 'node:assert/strict';
|
|
2
|
-
import { describe, it } from 'node:test';
|
|
3
|
-
import { parseMockResponse } from './parseMockResponse.js';
|
|
4
|
-
void describe('parseMockResponse()', () => {
|
|
5
|
-
void it('should parse protocol, statusCode, headers and body', () => assert.deepEqual(parseMockResponse([
|
|
6
|
-
`HTTP/1.1 202 Accepted`,
|
|
7
|
-
`Content-Length: 36`,
|
|
8
|
-
`Content-Type: application/json`,
|
|
9
|
-
``,
|
|
10
|
-
`{"desired":{"config":{"nod":null}}}`,
|
|
11
|
-
].join('\n')), {
|
|
12
|
-
statusCode: 202,
|
|
13
|
-
protocol: 'HTTP/1.1',
|
|
14
|
-
headers: {
|
|
15
|
-
'Content-Length': '36',
|
|
16
|
-
'Content-Type': 'application/json',
|
|
17
|
-
},
|
|
18
|
-
body: '{"desired":{"config":{"nod":null}}}',
|
|
19
|
-
}));
|
|
20
|
-
});
|
package/dist/src/randomString.js
DELETED
package/dist/src/requests.js
DELETED
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
import { ScanCommand } from '@aws-sdk/client-dynamodb';
|
|
2
|
-
import { unmarshall } from '@aws-sdk/util-dynamodb';
|
|
3
|
-
export const listRequests = async (db, requestsTable) => ((await db.send(new ScanCommand({ TableName: requestsTable }))).Items ?? [])
|
|
4
|
-
.map((item) => {
|
|
5
|
-
const i = unmarshall(item);
|
|
6
|
-
return {
|
|
7
|
-
...i,
|
|
8
|
-
headers: JSON.parse(i.headers),
|
|
9
|
-
};
|
|
10
|
-
})
|
|
11
|
-
.sort((i1, i2) => i1.timestamp.localeCompare(i2.timestamp));
|
|
@@ -1,18 +0,0 @@
|
|
|
1
|
-
import assert from 'node:assert';
|
|
2
|
-
import { describe, test as it } from 'node:test';
|
|
3
|
-
import { URLSearchParams } from 'node:url';
|
|
4
|
-
import { sortQuery, sortQueryString } from './sortQueryString.js';
|
|
5
|
-
void describe('sortQueryString', () => {
|
|
6
|
-
void it('should sort the query part of a mock URL', () => assert.deepStrictEqual(sortQueryString('api.nrfcloud.com/v1/location/agps?eci=73393515&tac=132&requestType=custom&mcc=397&mnc=73&customTypes=2'), 'api.nrfcloud.com/v1/location/agps?customTypes=2&eci=73393515&mcc=397&mnc=73&requestType=custom&tac=132'));
|
|
7
|
-
});
|
|
8
|
-
void describe('sortQuery', () => {
|
|
9
|
-
void it('should sort URLSearchParams', () => assert.equal(sortQuery(new URLSearchParams('eci=73393515&tac=132&requestType=custom&mcc=397&mnc=73&customTypes=2')), 'customTypes=2&eci=73393515&mcc=397&mnc=73&requestType=custom&tac=132'));
|
|
10
|
-
void it('should sort a Record', () => assert.equal(sortQuery({
|
|
11
|
-
eci: '73393515',
|
|
12
|
-
tac: '132',
|
|
13
|
-
requestType: 'custom',
|
|
14
|
-
mcc: '397',
|
|
15
|
-
mnc: '73',
|
|
16
|
-
customTypes: '2',
|
|
17
|
-
}), 'customTypes=2&eci=73393515&mcc=397&mnc=73&requestType=custom&tac=132'));
|
|
18
|
-
});
|
package/src/cli.ts
DELETED
|
@@ -1,109 +0,0 @@
|
|
|
1
|
-
import { CloudFormationClient } from '@aws-sdk/client-cloudformation'
|
|
2
|
-
import { GetCallerIdentityCommand, STSClient } from '@aws-sdk/client-sts'
|
|
3
|
-
import { stackOutput } from '@bifravst/cloudformation-helpers'
|
|
4
|
-
import run from '@bifravst/run'
|
|
5
|
-
import chalk from 'chalk'
|
|
6
|
-
import path, { dirname } from 'node:path'
|
|
7
|
-
import { fileURLToPath } from 'node:url'
|
|
8
|
-
import type { StackOutputs } from '../cdk/Stack.js'
|
|
9
|
-
import { randomString } from './randomString.js'
|
|
10
|
-
|
|
11
|
-
const die = (err: Error): void => {
|
|
12
|
-
console.error('')
|
|
13
|
-
console.error(chalk.yellow('⚠️'), chalk.red.bold(err.message))
|
|
14
|
-
console.error('')
|
|
15
|
-
console.error(err)
|
|
16
|
-
process.exit(1)
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
process.on('uncaughtException', die)
|
|
20
|
-
process.on('unhandledRejection', die)
|
|
21
|
-
|
|
22
|
-
const cdkApp = () => [
|
|
23
|
-
'--app',
|
|
24
|
-
`"npx tsx --no-warnings ${path.join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'cdk', 'http-api-mock.ts')}"`,
|
|
25
|
-
]
|
|
26
|
-
|
|
27
|
-
export const cli = async (): Promise<void> => {
|
|
28
|
-
await whoAmI()
|
|
29
|
-
if (process.argv.includes('destroy')) {
|
|
30
|
-
await destroy(getStackNameFromArgs('destroy'))
|
|
31
|
-
return
|
|
32
|
-
}
|
|
33
|
-
if (process.argv.includes('describe')) {
|
|
34
|
-
await describe(getStackNameFromArgs('describe'))
|
|
35
|
-
return
|
|
36
|
-
}
|
|
37
|
-
const stackName = `http-api-mock-${randomString()}`
|
|
38
|
-
console.error(chalk.yellow(`Stack name`), chalk.green(stackName))
|
|
39
|
-
|
|
40
|
-
await run({
|
|
41
|
-
command: 'npx',
|
|
42
|
-
args: ['cdk', ...cdkApp(), 'deploy', '--require-approval', 'never'],
|
|
43
|
-
env: {
|
|
44
|
-
...process.env,
|
|
45
|
-
HTTP_API_MOCK_STACK_NAME: stackName,
|
|
46
|
-
},
|
|
47
|
-
log: {
|
|
48
|
-
debug: (msg) => console.error(chalk.blueBright('[CDK]'), chalk.blue(msg)),
|
|
49
|
-
},
|
|
50
|
-
})
|
|
51
|
-
|
|
52
|
-
await describe(stackName)
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
const whoAmI = async (): Promise<{ Account: string }> => {
|
|
56
|
-
try {
|
|
57
|
-
const me = await new STSClient({}).send(new GetCallerIdentityCommand({}))
|
|
58
|
-
|
|
59
|
-
if (me.Account === undefined) throw new Error(`Not authenticated!`)
|
|
60
|
-
|
|
61
|
-
console.error(chalk.yellow('Account'), chalk.green(me.Account))
|
|
62
|
-
|
|
63
|
-
return {
|
|
64
|
-
Account: me.Account,
|
|
65
|
-
}
|
|
66
|
-
} catch (err) {
|
|
67
|
-
throw new Error(`Not authenticated!`)
|
|
68
|
-
}
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const destroy = async (stackName: string) => {
|
|
72
|
-
console.error(chalk.yellow(`Stack name`), chalk.green(stackName))
|
|
73
|
-
await run({
|
|
74
|
-
command: 'npx',
|
|
75
|
-
args: ['cdk', ...cdkApp(), 'destroy', '-f'],
|
|
76
|
-
env: {
|
|
77
|
-
...process.env,
|
|
78
|
-
HTTP_API_MOCK_STACK_NAME: stackName,
|
|
79
|
-
},
|
|
80
|
-
log: {
|
|
81
|
-
debug: (msg) => console.error(chalk.blueBright('[CDK]'), chalk.blue(msg)),
|
|
82
|
-
},
|
|
83
|
-
})
|
|
84
|
-
|
|
85
|
-
console.error(chalk.green(`Stack destroyed`))
|
|
86
|
-
}
|
|
87
|
-
|
|
88
|
-
const describe = async (stackName: string) => {
|
|
89
|
-
console.log(
|
|
90
|
-
JSON.stringify(
|
|
91
|
-
{
|
|
92
|
-
stackName,
|
|
93
|
-
...(await stackOutput(new CloudFormationClient({}))<StackOutputs>(
|
|
94
|
-
stackName,
|
|
95
|
-
)),
|
|
96
|
-
},
|
|
97
|
-
null,
|
|
98
|
-
2,
|
|
99
|
-
),
|
|
100
|
-
)
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
const getStackNameFromArgs = (command: string) => {
|
|
104
|
-
const stackName = process.argv[process.argv.indexOf(command) + 1]
|
|
105
|
-
if (stackName === undefined) {
|
|
106
|
-
throw new Error(`Must provide a stack name!`)
|
|
107
|
-
}
|
|
108
|
-
return stackName
|
|
109
|
-
}
|
package/src/mock.spec.ts
DELETED
|
@@ -1,52 +0,0 @@
|
|
|
1
|
-
import type { AttributeValue, DynamoDBClient } from '@aws-sdk/client-dynamodb'
|
|
2
|
-
import { unmarshall } from '@aws-sdk/util-dynamodb'
|
|
3
|
-
import assert from 'node:assert/strict'
|
|
4
|
-
import { describe, it, mock as testMock } from 'node:test'
|
|
5
|
-
import { mock } from './mock.js'
|
|
6
|
-
|
|
7
|
-
void describe('mock()', () => {
|
|
8
|
-
void it('should register a response', async () => {
|
|
9
|
-
const db = {
|
|
10
|
-
send: testMock.fn(async () => Promise.resolve(undefined)),
|
|
11
|
-
}
|
|
12
|
-
const httpApiMock = mock({
|
|
13
|
-
db: db as unknown as DynamoDBClient,
|
|
14
|
-
responsesTable: 'response-table',
|
|
15
|
-
})
|
|
16
|
-
|
|
17
|
-
await httpApiMock.response(`GET foo/bar?k=v`, {
|
|
18
|
-
status: 200,
|
|
19
|
-
headers: new Headers({
|
|
20
|
-
'content-type': 'application/json; charset=utf-8',
|
|
21
|
-
}),
|
|
22
|
-
body: JSON.stringify({
|
|
23
|
-
result: 'some-value',
|
|
24
|
-
}),
|
|
25
|
-
})
|
|
26
|
-
|
|
27
|
-
assert.equal(db.send.mock.callCount(), 1)
|
|
28
|
-
const [{ input: args }] = db.send.mock.calls[0]?.arguments as unknown as [
|
|
29
|
-
{
|
|
30
|
-
input: {
|
|
31
|
-
TableName: string
|
|
32
|
-
Item: Record<string, AttributeValue>
|
|
33
|
-
}
|
|
34
|
-
},
|
|
35
|
-
]
|
|
36
|
-
assert.equal(args.TableName, 'response-table')
|
|
37
|
-
const { methodPathQuery, statusCode, body, queryParams } = unmarshall(
|
|
38
|
-
args.Item,
|
|
39
|
-
)
|
|
40
|
-
assert.equal(statusCode, 200)
|
|
41
|
-
assert.equal(methodPathQuery, 'GET foo/bar?k=v')
|
|
42
|
-
assert.equal(
|
|
43
|
-
body,
|
|
44
|
-
[
|
|
45
|
-
`content-type: application/json; charset=utf-8`,
|
|
46
|
-
``,
|
|
47
|
-
JSON.stringify({ result: 'some-value' }),
|
|
48
|
-
].join('\n'),
|
|
49
|
-
)
|
|
50
|
-
assert.deepEqual(queryParams, { k: 'v' })
|
|
51
|
-
})
|
|
52
|
-
})
|
package/src/mock.ts
DELETED
|
@@ -1,61 +0,0 @@
|
|
|
1
|
-
import type { DynamoDBClient } from '@aws-sdk/client-dynamodb'
|
|
2
|
-
import { registerResponse } from './responses.js'
|
|
3
|
-
|
|
4
|
-
type MockResponseFn = (
|
|
5
|
-
// The expected request in the form 'GET resource/subresource?query=value
|
|
6
|
-
methodPathQuery: string,
|
|
7
|
-
// The response
|
|
8
|
-
response: Partial<{
|
|
9
|
-
headers: Headers
|
|
10
|
-
status: number
|
|
11
|
-
body: string
|
|
12
|
-
}>,
|
|
13
|
-
keep?: boolean,
|
|
14
|
-
) => Promise<void>
|
|
15
|
-
|
|
16
|
-
export const mockResponse =
|
|
17
|
-
(db: DynamoDBClient, responsesTable: string): MockResponseFn =>
|
|
18
|
-
async (methodPathQuery, response, keep) => {
|
|
19
|
-
const [method, pathWithQuery] = methodPathQuery.split(' ', 2)
|
|
20
|
-
if (!/^[A-Z]+$/.test(method ?? ''))
|
|
21
|
-
throw new Error(`Invalid method ${method} in ${methodPathQuery}!`)
|
|
22
|
-
if (pathWithQuery === undefined)
|
|
23
|
-
throw new Error(`Missing path in ${methodPathQuery}!`)
|
|
24
|
-
const [path, query] = pathWithQuery.split('?', 2) as [
|
|
25
|
-
string,
|
|
26
|
-
string | undefined,
|
|
27
|
-
]
|
|
28
|
-
if (path.startsWith('/'))
|
|
29
|
-
throw new Error(`Path ${path} must not start with /!`)
|
|
30
|
-
|
|
31
|
-
const bodyParts = []
|
|
32
|
-
if (response.headers !== undefined) {
|
|
33
|
-
for (const [k, v] of response.headers.entries()) {
|
|
34
|
-
bodyParts.push(`${k}: ${v}`)
|
|
35
|
-
}
|
|
36
|
-
bodyParts.push('')
|
|
37
|
-
}
|
|
38
|
-
if (response.body !== undefined) bodyParts.push(response.body)
|
|
39
|
-
await registerResponse(db, responsesTable, {
|
|
40
|
-
path,
|
|
41
|
-
method: method ?? 'GET',
|
|
42
|
-
queryParams: new URLSearchParams(query),
|
|
43
|
-
body: bodyParts.length > 0 ? bodyParts.join('\n') : undefined,
|
|
44
|
-
statusCode: response.status,
|
|
45
|
-
keep,
|
|
46
|
-
})
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
export type HttpAPIMock = {
|
|
50
|
-
response: MockResponseFn
|
|
51
|
-
}
|
|
52
|
-
|
|
53
|
-
export const mock = ({
|
|
54
|
-
db,
|
|
55
|
-
responsesTable,
|
|
56
|
-
}: {
|
|
57
|
-
db: DynamoDBClient
|
|
58
|
-
responsesTable: string
|
|
59
|
-
}): HttpAPIMock => ({
|
|
60
|
-
response: mockResponse(db, responsesTable),
|
|
61
|
-
})
|
|
@@ -1,30 +0,0 @@
|
|
|
1
|
-
import assert from 'node:assert/strict'
|
|
2
|
-
import { describe, it } from 'node:test'
|
|
3
|
-
import { parseMockRequest } from './parseMockRequest.js'
|
|
4
|
-
|
|
5
|
-
void describe('parseMockRequest()', () => {
|
|
6
|
-
void it('should parse method, resource, protocol, headers and body', () =>
|
|
7
|
-
assert.deepEqual(
|
|
8
|
-
parseMockRequest(
|
|
9
|
-
[
|
|
10
|
-
`PATCH /v1/devices/foo/state HTTP/1.1`,
|
|
11
|
-
`Content-Length: 36`,
|
|
12
|
-
`Content-Type: application/json`,
|
|
13
|
-
`If-Match: 8835`,
|
|
14
|
-
``,
|
|
15
|
-
`{"desired":{"config":{"nod":null}}}`,
|
|
16
|
-
].join('\n'),
|
|
17
|
-
),
|
|
18
|
-
{
|
|
19
|
-
method: 'PATCH',
|
|
20
|
-
resource: '/v1/devices/foo/state',
|
|
21
|
-
protocol: 'HTTP/1.1',
|
|
22
|
-
headers: {
|
|
23
|
-
'Content-Length': '36',
|
|
24
|
-
'Content-Type': 'application/json',
|
|
25
|
-
'If-Match': '8835',
|
|
26
|
-
},
|
|
27
|
-
body: '{"desired":{"config":{"nod":null}}}',
|
|
28
|
-
},
|
|
29
|
-
))
|
|
30
|
-
})
|
package/src/parseMockRequest.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
export const parseMockRequest = (
|
|
2
|
-
r: string,
|
|
3
|
-
): {
|
|
4
|
-
method: string
|
|
5
|
-
resource: string
|
|
6
|
-
protocol: string // 'HTTP/1.0' | 'HTTP/1.1'
|
|
7
|
-
headers: Record<string, string>
|
|
8
|
-
body: string
|
|
9
|
-
} => {
|
|
10
|
-
const lines = r.split('\n')
|
|
11
|
-
const methodResourceProtol = lines.shift()
|
|
12
|
-
const blankLineLocation = lines.indexOf('')
|
|
13
|
-
const headerLines =
|
|
14
|
-
blankLineLocation === -1 ? lines : lines.slice(0, blankLineLocation)
|
|
15
|
-
const body =
|
|
16
|
-
blankLineLocation === -1
|
|
17
|
-
? ''
|
|
18
|
-
: lines.slice(blankLineLocation + 1).join('\n')
|
|
19
|
-
|
|
20
|
-
const requestInfo =
|
|
21
|
-
/^(?<method>[A-Z]+) (?<resource>[^ ]+) (?<protocol>HTTP\/[0-9.]+)/.exec(
|
|
22
|
-
methodResourceProtol ?? '',
|
|
23
|
-
)?.groups as { method: string; resource: string; protocol: string }
|
|
24
|
-
|
|
25
|
-
if (requestInfo === null)
|
|
26
|
-
throw new Error(`Invalid request info: ${methodResourceProtol}`)
|
|
27
|
-
|
|
28
|
-
return {
|
|
29
|
-
...requestInfo,
|
|
30
|
-
headers: headerLines
|
|
31
|
-
.map((s) => s.split(':', 2))
|
|
32
|
-
.reduce((headers, [k, v]) => ({ ...headers, [k ?? '']: v?.trim() }), {}),
|
|
33
|
-
body,
|
|
34
|
-
}
|
|
35
|
-
}
|
|
@@ -1,27 +0,0 @@
|
|
|
1
|
-
import assert from 'node:assert/strict'
|
|
2
|
-
import { describe, it } from 'node:test'
|
|
3
|
-
import { parseMockResponse } from './parseMockResponse.js'
|
|
4
|
-
|
|
5
|
-
void describe('parseMockResponse()', () => {
|
|
6
|
-
void it('should parse protocol, statusCode, headers and body', () =>
|
|
7
|
-
assert.deepEqual(
|
|
8
|
-
parseMockResponse(
|
|
9
|
-
[
|
|
10
|
-
`HTTP/1.1 202 Accepted`,
|
|
11
|
-
`Content-Length: 36`,
|
|
12
|
-
`Content-Type: application/json`,
|
|
13
|
-
``,
|
|
14
|
-
`{"desired":{"config":{"nod":null}}}`,
|
|
15
|
-
].join('\n'),
|
|
16
|
-
),
|
|
17
|
-
{
|
|
18
|
-
statusCode: 202,
|
|
19
|
-
protocol: 'HTTP/1.1',
|
|
20
|
-
headers: {
|
|
21
|
-
'Content-Length': '36',
|
|
22
|
-
'Content-Type': 'application/json',
|
|
23
|
-
},
|
|
24
|
-
body: '{"desired":{"config":{"nod":null}}}',
|
|
25
|
-
},
|
|
26
|
-
))
|
|
27
|
-
})
|
package/src/parseMockResponse.ts
DELETED
|
@@ -1,35 +0,0 @@
|
|
|
1
|
-
export const parseMockResponse = (
|
|
2
|
-
r: string,
|
|
3
|
-
): {
|
|
4
|
-
statusCode: number
|
|
5
|
-
protocol: string // 'HTTP/1.0' | 'HTTP/1.1'
|
|
6
|
-
headers: Record<string, string>
|
|
7
|
-
body: string
|
|
8
|
-
} => {
|
|
9
|
-
const lines = r.split('\n')
|
|
10
|
-
const protocolStatusCode = lines.shift()
|
|
11
|
-
const blankLineLocation = lines.indexOf('')
|
|
12
|
-
const headerLines =
|
|
13
|
-
blankLineLocation === -1 ? lines : lines.slice(0, blankLineLocation)
|
|
14
|
-
const body =
|
|
15
|
-
blankLineLocation === -1
|
|
16
|
-
? ''
|
|
17
|
-
: lines.slice(blankLineLocation + 1).join('\n')
|
|
18
|
-
|
|
19
|
-
const responseInfo =
|
|
20
|
-
/^(?<protocol>HTTP\/[0-9.]+) (?<statusCode>[0-9]+) /.exec(
|
|
21
|
-
protocolStatusCode ?? '',
|
|
22
|
-
)?.groups as { statusCode: string; protocol: string }
|
|
23
|
-
|
|
24
|
-
if (responseInfo === null)
|
|
25
|
-
throw new Error(`Invalid request info: ${protocolStatusCode}`)
|
|
26
|
-
|
|
27
|
-
return {
|
|
28
|
-
statusCode: parseInt(responseInfo.statusCode, 10),
|
|
29
|
-
protocol: responseInfo.protocol,
|
|
30
|
-
headers: headerLines
|
|
31
|
-
.map((s) => s.split(':', 2))
|
|
32
|
-
.reduce((headers, [k, v]) => ({ ...headers, [k ?? '']: v?.trim() }), {}),
|
|
33
|
-
body,
|
|
34
|
-
}
|
|
35
|
-
}
|
package/src/randomString.ts
DELETED
package/src/requests.ts
DELETED
|
@@ -1,28 +0,0 @@
|
|
|
1
|
-
import { ScanCommand, type DynamoDBClient } from '@aws-sdk/client-dynamodb'
|
|
2
|
-
import { unmarshall } from '@aws-sdk/util-dynamodb'
|
|
3
|
-
|
|
4
|
-
export type Request = {
|
|
5
|
-
path: string //e.g.'555c3960-2092-438b-b2b0-f28eebd1f5bb'
|
|
6
|
-
query: null
|
|
7
|
-
timestamp: string //e.g.'2024-04-05T13:01:14.434Z'
|
|
8
|
-
ttl: string //e.g. 1712322374
|
|
9
|
-
headers: Record<string, string> //e.g. '{"Accept":"*/*","Accept-Encoding":"br, gzip, deflate","Accept-Language":"*","CloudFront-Forwarded-Proto":"https","CloudFront-Is-Desktop-Viewer":"true","CloudFront-Is-Mobile-Viewer":"false","CloudFront-Is-SmartTV-Viewer":"false","CloudFront-Is-Tablet-Viewer":"false","CloudFront-Viewer-ASN":"2116","CloudFront-Viewer-Country":"NO","Host":"idj1fffo0k.execute-api.eu-west-1.amazonaws.com","sec-fetch-mode":"cors","User-Agent":"node","Via":"1.1 b053873243f91b1bb6dc406ce0c67db4.cloudfront.net (CloudFront)","X-Amz-Cf-Id":"_vJIGo6Z89QxDzoqOZL4G0PQqPFWGesVXVan4ND934_Urqn2ifSOsQ==","X-Amzn-Trace-Id":"Root=1-660ff61a-25e1219a7f153e1b0c768358","X-Forwarded-For":"194.19.86.146, 130.176.182.18","X-Forwarded-Port":"443","X-Forwarded-Proto":"https"}'
|
|
10
|
-
method: string //e.g.'GET'
|
|
11
|
-
requestId: string //e.g.'f34b042b-e9a2-4089-97a2-241516d40d64'
|
|
12
|
-
body: string //e.g.'{}'
|
|
13
|
-
methodPathQuery: string //e.g.'GET 555c3960-2092-438b-b2b0-f28eebd1f5bb'
|
|
14
|
-
}
|
|
15
|
-
|
|
16
|
-
export const listRequests = async (
|
|
17
|
-
db: DynamoDBClient,
|
|
18
|
-
requestsTable: string,
|
|
19
|
-
): Promise<Array<Request>> =>
|
|
20
|
-
((await db.send(new ScanCommand({ TableName: requestsTable }))).Items ?? [])
|
|
21
|
-
.map((item) => {
|
|
22
|
-
const i = unmarshall(item)
|
|
23
|
-
return {
|
|
24
|
-
...i,
|
|
25
|
-
headers: JSON.parse(i.headers),
|
|
26
|
-
} as Request
|
|
27
|
-
})
|
|
28
|
-
.sort((i1, i2) => i1.timestamp.localeCompare(i2.timestamp))
|