@bizhermit/next-absorber
v1.1.1
Published
absorber for nexpress and nextron
Downloads
5
Maintainers
Readme
Next absorber
@bizhermit/nexpress and @bizhermit/nextron absorber
Usage
Install
npm i @bizhermit/next-absorber
Example
back-end
// src/pages/api/hello.ts
import ApiContext from "@bizhermit/next-absorber/dist/api-context";
import type { NextApiRequest, NextApiResponse } from "next";
const handler = (req: NextApiRequest, res: NextApiResponse) => {
const ctx = new ApiContext(req, res);
try {
const params = ctx.getParams(); // get body params
console.log(params); // => { action: "test" }
let count = ctx.getSession<number>("count") ?? 0;
count++;
ctx.setSession("count", count);
ctx.addInformation("success!");
ctx.done({ count }); // return code:200
} catch(err) {
ctx.error(err); // return code:500
}
};
export default handler;
front-end
// src/pages/index.tsx
import fetchApi from "@bizhermit/next-absorber/dist/fetch";
const Component = () => {
const func = async () => {
const res = await fetchApi("hello", { action: "test" });
const messages = res.messages;
console.log(messages); // => [{ title: "", message: "success!", type: "info" }]
if (res.hasError()) {
// error action
return;
}
const data = res.data;
console.log(data); // => { count: 1 }
};
return <button onClick={func}>fetch api</button>;
};