http-json-contract 0.0.0-stage → 0.1.1
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/README.md +98 -2
- package/dist/index.d.ts +8 -0
- package/dist/index.js +64 -0
- package/package.json +46 -4
package/README.md
CHANGED
|
@@ -1,3 +1,99 @@
|
|
|
1
|
-
#
|
|
1
|
+
# http-json-contract
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Rust 서버의 HTTP JSON 응답을 **기존 TypeScript 파서로 읽어**, 앱이 의존하는 값과 동작이 그대로인지 검사하는 라이브러리입니다. HTTP 200과 유효한 JSON을 받아도 필드 누락, 이름 변경, 기본값 적용 때문에 앱의 동작은 달라질 수 있습니다.
|
|
4
|
+
|
|
5
|
+
[npm 패키지](https://www.npmjs.com/package/http-json-contract) · [GitHub 저장소와 예제](https://github.com/IMHOJEONG/http-json-contract)
|
|
6
|
+
|
|
7
|
+
## npm으로 설치
|
|
8
|
+
|
|
9
|
+
Node.js 22.18 이상에서 사용할 수 있는 ESM 패키지이며, 런타임 의존성이 없습니다. 기존 TypeScript 프로젝트에서 개발 의존성으로 설치합니다.
|
|
10
|
+
|
|
11
|
+
```bash
|
|
12
|
+
npm install -D http-json-contract
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
## 실제 Rust 서버와 첫 계약 테스트 실행
|
|
16
|
+
|
|
17
|
+
### 1. Rust 서버 실행
|
|
18
|
+
|
|
19
|
+
별도 터미널에서 이 저장소를 복제하고 [Axum 예제 서버](examples/rust/src/main.rs)를 실행합니다. Rust와 Cargo가 필요합니다.
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
git clone https://github.com/IMHOJEONG/http-json-contract.git
|
|
23
|
+
cd http-json-contract
|
|
24
|
+
cargo run --locked --manifest-path examples/rust/Cargo.toml
|
|
25
|
+
```
|
|
26
|
+
|
|
27
|
+
서버는 임시 포트에 바인딩한 뒤 `http://127.0.0.1:49152` 같은 주소를 출력합니다. `GET /preferences`는 `emailNotifications: false`를 보내고, `?rename_field=true`를 붙이면 같은 값을 `email_notifications`라는 이름으로 보냅니다.
|
|
28
|
+
|
|
29
|
+
### 2. TypeScript 소비자에서 테스트 작성
|
|
30
|
+
|
|
31
|
+
npm 패키지를 설치한 TypeScript 프로젝트에 아래 코드를 `preferences.contract.test.mts`로 저장합니다. 예제 파서는 이전 응답과의 호환을 위해 필드가 없으면 `true`를 사용합니다. 실제 프로젝트에서는 이 함수를 앱의 기존 파서 import로 바꾸세요. [전체 소비자 테스트](examples/rust/consumer/contract.test.ts)
|
|
32
|
+
|
|
33
|
+
```ts
|
|
34
|
+
import assert from "node:assert/strict";
|
|
35
|
+
import { test } from "node:test";
|
|
36
|
+
import { createJsonContractClient } from "http-json-contract";
|
|
37
|
+
|
|
38
|
+
const baseUrl = process.env.API_BASE_URL;
|
|
39
|
+
assert.ok(baseUrl, "Set API_BASE_URL to the URL printed by the Rust server");
|
|
40
|
+
|
|
41
|
+
const api = createJsonContractClient({ baseUrl });
|
|
42
|
+
|
|
43
|
+
function parsePreferences(body: string) {
|
|
44
|
+
const value: unknown = JSON.parse(body);
|
|
45
|
+
if (value === null || typeof value !== "object") {
|
|
46
|
+
throw new TypeError("Expected a preferences object");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
const enabled =
|
|
50
|
+
"emailNotifications" in value ? value.emailNotifications : true;
|
|
51
|
+
if (typeof enabled !== "boolean") {
|
|
52
|
+
throw new TypeError("Expected emailNotifications to be a boolean");
|
|
53
|
+
}
|
|
54
|
+
return { emailNotifications: enabled };
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
test("preserves an explicit email notification opt-out", async () => {
|
|
58
|
+
const path =
|
|
59
|
+
process.env.RENAME_FIELD === "1"
|
|
60
|
+
? "/preferences?rename_field=true"
|
|
61
|
+
: "/preferences";
|
|
62
|
+
const preferences = await api.get(path, parsePreferences);
|
|
63
|
+
assert.equal(preferences.emailNotifications, false, "emailNotifications");
|
|
64
|
+
});
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### 3. 정상 응답과 회귀 비교
|
|
68
|
+
|
|
69
|
+
아래 주소를 서버가 출력한 실제 주소로 바꿉니다. 첫 번째 실행은 통과합니다. 두 번째 실행은 HTTP 200을 받고 파싱에도 성공하지만, 파서가 바뀐 필드 이름을 인식하지 못해 `false` 대신 `true`를 반환하므로 실패합니다.
|
|
70
|
+
|
|
71
|
+
```bash
|
|
72
|
+
export API_BASE_URL=http://127.0.0.1:49152
|
|
73
|
+
node --test preferences.contract.test.mts
|
|
74
|
+
RENAME_FIELD=1 node --test preferences.contract.test.mts
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
## 공개 API
|
|
78
|
+
|
|
79
|
+
- `createJsonContractClient({ baseUrl, timeoutMs })`에 경로나 인증 정보가 없는 HTTP(S) origin을 넘깁니다. 타임아웃의 기본값은 5초입니다.
|
|
80
|
+
- `client.get(path, parse)`는 같은 origin의 경로와 동기 또는 비동기 파서를 받습니다. 경로에 쿼리 문자열을 붙일 수 있습니다.
|
|
81
|
+
- HTTP 200과 `application/json` 또는 `application/*+json`을 확인한 뒤 응답 본문 원문을 파서에 전달합니다. 반환 타입은 파서에서 추론되며, 앱이 어떤 값에 의존하는지는 각 테스트에서 단언합니다.
|
|
82
|
+
|
|
83
|
+
## GitHub Actions에서 실행
|
|
84
|
+
|
|
85
|
+
[워크플로 전체 설정](.github/workflows/rust-http-json-contract.yml)은 PR, `main` 푸시, 수동 실행에서 작동합니다. [`.node-version`](.node-version)의 Node.js와 Rust 1.96.0을 설치한 뒤, 아래 명령을 실행합니다.
|
|
86
|
+
|
|
87
|
+
```yaml
|
|
88
|
+
- name: Install dependencies
|
|
89
|
+
run: pnpm install --frozen-lockfile --ignore-scripts
|
|
90
|
+
|
|
91
|
+
- name: Pack the npm package and test the real Rust server
|
|
92
|
+
run: pnpm test:example
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
[`test:example` 실행 스크립트](examples/rust/run.sh)는 패키지를 빌드하고 생성한 tarball을 임시 TypeScript 프로젝트에 설치합니다. 그다음 실제 Rust 서버를 실행해 준비된 주소를 `API_BASE_URL`로 넘기고, 테스트가 끝나면 서버를 종료합니다. [예제 테스트](examples/rust/consumer/contract.test.ts)는 큰 문서 ID와 `null`·필드 누락을 구분하고, 알림 수신 거부를 유지하며, 필드 이름을 변경하면 정확한 단언 오류가 발생하는지 확인합니다. 같은 명령을 저장소 루트에서 실행하면 로컬에서도 확인할 수 있습니다.
|
|
96
|
+
|
|
97
|
+
## 브라우저 데모
|
|
98
|
+
|
|
99
|
+
의존성을 설치한 뒤 `pnpm demo`를 실행하고 터미널에 출력된 주소를 엽니다. 정상 응답과 필드 이름 변경의 결과를 화면에서 비교할 수 있습니다.
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export interface JsonContractOptions {
|
|
2
|
+
baseUrl: string | URL;
|
|
3
|
+
timeoutMs?: number;
|
|
4
|
+
}
|
|
5
|
+
export interface JsonContractClient {
|
|
6
|
+
get<T>(path: string, parse: (body: string) => T | Promise<T>): Promise<T>;
|
|
7
|
+
}
|
|
8
|
+
export declare function createJsonContractClient({ baseUrl, timeoutMs, }: JsonContractOptions): JsonContractClient;
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
export function createJsonContractClient({ baseUrl, timeoutMs = 5_000, }) {
|
|
2
|
+
const base = new URL(baseUrl);
|
|
3
|
+
if (!["http:", "https:"].includes(base.protocol) ||
|
|
4
|
+
base.href !== base.origin + "/") {
|
|
5
|
+
throw new TypeError("baseUrl must be an HTTP(S) origin");
|
|
6
|
+
}
|
|
7
|
+
if (!Number.isInteger(timeoutMs) ||
|
|
8
|
+
timeoutMs < 1 ||
|
|
9
|
+
timeoutMs > 2_147_483_647) {
|
|
10
|
+
throw new RangeError("timeoutMs must be an integer between 1 and 2147483647");
|
|
11
|
+
}
|
|
12
|
+
return {
|
|
13
|
+
async get(path, parse) {
|
|
14
|
+
const url = new URL(path, base);
|
|
15
|
+
if (!path.startsWith("/") ||
|
|
16
|
+
url.origin !== base.origin ||
|
|
17
|
+
url.href.includes("#")) {
|
|
18
|
+
throw new TypeError("path must be a same-origin URL path without a fragment");
|
|
19
|
+
}
|
|
20
|
+
const endpoint = "GET " + url.pathname;
|
|
21
|
+
let response;
|
|
22
|
+
try {
|
|
23
|
+
response = await fetch(url, {
|
|
24
|
+
headers: { accept: "application/json" },
|
|
25
|
+
redirect: "manual",
|
|
26
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
27
|
+
});
|
|
28
|
+
}
|
|
29
|
+
catch (cause) {
|
|
30
|
+
throw new Error(endpoint + ": request failed", { cause });
|
|
31
|
+
}
|
|
32
|
+
if (response.status !== 200) {
|
|
33
|
+
await response.body?.cancel().catch(() => { });
|
|
34
|
+
throw new Error(endpoint + ": expected HTTP 200, received " + response.status);
|
|
35
|
+
}
|
|
36
|
+
const contentType = response.headers.get("content-type");
|
|
37
|
+
const mediaType = contentType?.split(";", 1)[0]?.trim().toLowerCase();
|
|
38
|
+
if (mediaType !== "application/json" &&
|
|
39
|
+
!/^application\/[\w.+-]+\+json$/.test(mediaType ?? "")) {
|
|
40
|
+
await response.body?.cancel().catch(() => { });
|
|
41
|
+
throw new Error(endpoint +
|
|
42
|
+
": expected JSON, received " +
|
|
43
|
+
(contentType ?? "no content type"));
|
|
44
|
+
}
|
|
45
|
+
let raw;
|
|
46
|
+
try {
|
|
47
|
+
raw = await response.text();
|
|
48
|
+
}
|
|
49
|
+
catch (cause) {
|
|
50
|
+
throw new Error(endpoint + ": could not read the response body", {
|
|
51
|
+
cause,
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
try {
|
|
55
|
+
return await parse(raw);
|
|
56
|
+
}
|
|
57
|
+
catch (cause) {
|
|
58
|
+
throw new Error(endpoint + ": consumer parser rejected the response", {
|
|
59
|
+
cause,
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
},
|
|
63
|
+
};
|
|
64
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,48 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "http-json-contract",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "HTTP JSON contract testing with your existing TypeScript parser. Includes Rust and GitHub Actions examples.",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"contract-testing",
|
|
7
|
+
"consumer-contract-testing",
|
|
8
|
+
"api-testing",
|
|
9
|
+
"integration-testing",
|
|
10
|
+
"http",
|
|
11
|
+
"json",
|
|
12
|
+
"typescript",
|
|
13
|
+
"rust",
|
|
14
|
+
"axum",
|
|
15
|
+
"nodejs"
|
|
16
|
+
],
|
|
17
|
+
"repository": {
|
|
18
|
+
"type": "git",
|
|
19
|
+
"url": "git+https://github.com/IMHOJEONG/http-json-contract.git"
|
|
20
|
+
},
|
|
21
|
+
"homepage": "https://github.com/IMHOJEONG/http-json-contract#readme",
|
|
22
|
+
"bugs": {
|
|
23
|
+
"url": "https://github.com/IMHOJEONG/http-json-contract/issues"
|
|
24
|
+
},
|
|
25
|
+
"type": "module",
|
|
26
|
+
"files": [
|
|
27
|
+
"dist",
|
|
28
|
+
"README.md"
|
|
29
|
+
],
|
|
30
|
+
"exports": {
|
|
31
|
+
".": {
|
|
32
|
+
"types": "./dist/index.d.ts",
|
|
33
|
+
"import": "./dist/index.js"
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
"scripts": {
|
|
37
|
+
"build": "tsc -p tsconfig.build.json",
|
|
38
|
+
"test:example": "pnpm build && bash examples/rust/run.sh",
|
|
39
|
+
"demo": "tsc -p examples/rust/web/tsconfig.json && cargo run --locked --manifest-path examples/rust/Cargo.toml --features browser-demo"
|
|
40
|
+
},
|
|
41
|
+
"devDependencies": {
|
|
42
|
+
"typescript": "6.0.3"
|
|
43
|
+
},
|
|
44
|
+
"engines": {
|
|
45
|
+
"node": ">=22.18.0"
|
|
46
|
+
},
|
|
47
|
+
"packageManager": "pnpm@12.14.0"
|
|
48
|
+
}
|