Skip to content

Commit

Permalink
Add typed JSON.stringify
Browse files Browse the repository at this point in the history
  • Loading branch information
mpppk committed Jun 3, 2024
1 parent 429e1d0 commit 7430e98
Show file tree
Hide file tree
Showing 8 changed files with 855 additions and 13 deletions.
7 changes: 7 additions & 0 deletions .idea/prettier.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

32 changes: 22 additions & 10 deletions examples/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,34 @@
import { PathMap } from "./spec";
import { TFetch } from "../src";
import { JSON$stringifyT } from "../src/json";
import { unreachable } from "../src/utils";

const fetchT = fetch as TFetch<typeof origin, PathMap>;
const origin = "http://localhost:3000";
const headers = { "Content-Type": "application/json" };
// stringify is same as JSON.stringify but with type information
const stringify = JSON.stringify as JSON$stringifyT;

const main = async () => {
{
const path = `${origin}/users`;
const method = "get";
const res = await fetchT(path, { method });
if (res.ok) {
// r is the response schema defined in pathMap["/users"]["get"].res["20X"]
const r = await res.json();
console.log(`${path}:${method} => ${r.userNames}`);
} else {
// e is the response schema defined in pathMap["/users"]["get"].res other than "20X"
const e = await res.json();
console.log(`${path}:${method} => ${e.errorMessage}`);
switch (res.status) {
case 200: {
// r is the response schema defined in pathMap["/users"]["get"].res["200"]
const r = await res.json();
console.log(`${path}:${method} => ${r.userNames}`);
break;
}
case 400: {
// e is the response schema defined in pathMap["/users"]["get"].res["400"]
const e = await res.json();
console.log(`${path}:${method} => ${e.errorMessage}`);
break;
}
default:
unreachable(res);
}
}

Expand All @@ -44,8 +55,9 @@ const main = async () => {
const res = await fetchT(path, {
method,
headers,
// TODO: Add type information for body
body: JSON.stringify({ userName: "user1" }),
// body is the request schema defined in pathMap["/users"]["post"].body
// stringify is same as JSON.stringify but with type information
body: stringify({ userName: "user1" }),
});
if (res.ok) {
// r is the response schema defined in pathMap["/users"]["post"].res["20X"]
Expand Down
Loading

0 comments on commit 7430e98

Please sign in to comment.