Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add typed JSON.stringify #3

Merged
merged 1 commit into from
Jun 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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