0.0.1 • Published 2 years ago
atomic-api v0.0.1
Atomic API
WARNING: This is Work-In-Progress!
Use atomic-router as your router for Node.js backend
Install
npm install atomic-router atomic-api
Usage
- Create API controls
// @/shared/api
import { createApiControls } from "atomic-api";
// Returns { $method, $response } stores
export const apiControls = createApiControls();
- Create API route
// @/routes/post
import { createApiRoute } from "atomic-api";
import { apiControls } from "@/shared/api";
export type PostParams = {
postId: string;
};
export const post = createApiRoute({
controls: apiControls,
api: {
GET: ({ params }) => {
return {
id: params.postId,
title: "Some Post",
};
},
},
});
// `createApiRoute` returns this
post.route; // Route created by atomic-router
post.api.GET; // Effect<RouteParamsAndQuery<PostParams>, ...>
- Create a router
// @/app/router
import { createHistoryRouter } from "atomic-router";
import { post } from "@/routes/post";
export const routes = [{ path: "/posts/:postId", route: post.route }];
export const router = createHistoryRouter({
routes,
});
- Create a server
// @/app/server
import { createHttpServer } from "atomic-api";
import { router } from "@/app/router";
import { apiControls } from "@/shared/api";
export const server = createHttpServer({
router,
controls: apiControls,
});
server.listen(3002);
How does it work?
createHttpServer
starts a server (viahttp.createServer
)- On each request:
2.1. Triggerfork
and creates a newscope
2.2. Storereq.method
inapiControls.$method
2.3. Createhistory
instance and pushesreq.url
to it 2.4. Triggerrouter.setHistory
with a passedscope
2.5. Router opens matched route 2.6. CheckapiControls.$method
and open matching sub-route (created bychainRoute
) 2.7. Trigger effect and wait until it's finished 2.8.effect.doneData
writes its response toapiControls.$response
2.9. Triggerres.send
withapiControls.$response
data
TODO:
- Actually send response
- Pass req/res instance to effects
- Redirects
0.0.1
2 years ago