Created
August 1, 2022 19:35
-
-
Save glommer/ce1a487f23c6da577cc3557b9a288fc6 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import type { Post } from "../../chiselstrike/Post"; | |
export type { Post } from "../../chiselstrike/Post"; | |
function chiselUrl(name: string): string { | |
// Use environment variables to figure out where we are. Feel free to add this | |
// to your .env, but to keep things simple we'll add a default | |
const chiselServer = process.env.CHISEL_SERVER ?? "http://localhost:8080"; | |
// Which version? Versions are isolated backends that can be used in the same | |
// chisel instance. You can do test databases, API versions, or what your heart | |
// desires. By (local) default this is "dev", but when deployed it is customary | |
// for this to be "main" (github's main branch) or a PR number. | |
const chiselVersion = process.env.CHISEL_VERSION ?? "dev"; | |
return `${chiselServer}/${chiselVersion}/${name}`; | |
} | |
// In practice you could use a higher level library here such as Axios, or | |
// even hide everything behind tRPC. We are open coding fetches so it becomes | |
// abundandtly obvious that those are really just HTTP endpoints! | |
// | |
// You can do anything you want with them, including going headless, microservices, etc. | |
// The first function just gets all posts. No pagination, no filtering, though all of that | |
// can be easily added! | |
export async function getPosts(): Promise<Array<Post>> { | |
const url = chiselUrl("posts"); | |
console.log(url); | |
return fetch(url).then((response) => { | |
return response.json().then((crud) => { | |
return crud.results; // See how the example curl command returned: the actual data is on the `results` property | |
}); | |
}); | |
} | |
// The second function will just call the POST endpoint and create an object. | |
export async function createPost(post) { | |
const url = chiselUrl("posts"); | |
return fetch(url, { | |
method: "post", | |
body: JSON.stringify(post), | |
headers: { "Content-Type": "application/json" }, | |
}); | |
} | |
// Last option is to get a post, given its ID. With this, we have everything we need! | |
export async function getPost(id: string): Promise<Post> { | |
const url = `${chiselUrl("posts")}/${id}`; | |
return fetch(url).then((response) => { | |
return response.json(); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment