splake v0.3.1
splake
A very tiny router. Primarily designed for Next.js or Node.js HTTP Server.
Installation
npm install splake
// or
yarn add splake
Usage
splake
is often used in API Routes:
// pages/api/index.js
import splake from "splake";
const handler = splake()
.use(someMiddleware())
.get((req, res) => {
res.send("Hello fish frienz");
})
.post((req, res) => {
res.json({ hello: "fish frienz" });
})
.put(async (req, res) => {
res.end("async/await is supported");
})
.patch(async (req, res) => {
throw new Error("You can catch a error,
but not a splake my friend!");
});
export default handler;
For usage in pages with getServerSideProps
, see .run
.
API
The API is similar to Express.js or Connect.
splake(options)
Initialize an instance of splake
.
options.onError
Accepts a function as a catch-all error handler; executed whenever a middleware throws an error.
By default, it responses with status code 500
and error message if any.
function onError(err, req, res, next) {
logger.log(err);
res.status(500).end(err.toString());
// OR
next();
}
const handler = splake({ onError });
handler
.use((req, res, next) => {
throw new Error("oopsies!");
// or use next
next(Error("oopsies"));
})
.use((req, res) => {
// this will run if next() is called in onError
res.end("no more oopsies");
});
options.onNoMatch
Accepts a function of (req, res)
as a handler when no route is matched.
By default, it responses with 404
status and not found
body.
function onNoMatch(req, res) {
res.status(404).end("page not found.. sadface");
}
const handler = splake({ onNoMatch });
.use(base, ...fn)
base
(optional) - match all route to the right of base
or match all if omitted.
fn
(s) are functions of (req, res[, next])
or instance of splake
, where it will act as a sort of subunit of application.
// Mount middleware function
handler.use((req, res, next) => {
req.hello = "world";
// call next if you want continue...
next();
});
// Or include base
handler.use("/fishes", fn); // Only run in /foo/**
// Mount instance of splake
const common = splake().use(middleware1).use(middleware2); // You may have some common middleware to be used in every route.
const auth = splake().use("/home", verifyAuth);
const smolFish = splake().get(getHandle).post("/pikesrock", postHandle);
handler
.use(common) // `middleware1` and `middleware2` runs everywhere
.use(auth) // `verifyAuth` runs on /home/*
.use("/fishes", smolFish); // `getHandle` runs on /foo while `postHandle` runs on /fishes/pikesrock
// You can use a library too.
handler.use(passport.initialize());
.METHOD(pattern, ...fns)
METHOD
is a HTTP method (GET
, HEAD
, POST
, PUT
, PATCH
, DELETE
, OPTIONS
, TRACE
) in lowercase.
pattern
(optional) - match all route based on pattern or match all if omitted.
handler.use("/user", passport.initialize());
handler.get("/user", (req, res, next) => {
res.json(req.user);
});
handler.post("/users", (req, res, next) => {
res.end("User created");
});
handler.put("/user/:id", (req, res, next) => {
// https://nextjs.org/docs/routing/dynamic-routes
res.end(`User ${req.query.id} updated`);
});
handler.get((req, res, next) => {
res.end("This matches any given route");
});
Since Next.js already handles routing (including dynamic routes), we often omit pattern
in .METHOD
.
.all(pattern, ...fns)
Same as .METHOD but accepts any methods.
.run(req, res)
Runs req
and res
the middleware and returns a promise. It will not render 404
on not found or onError
on error.
This can be useful in getServerSideProps
.
// page/index.js
export async function getServerSideProps({ req, res }) {
const handler = splake().use(passport.initialize()).post(postMiddleware);
try {
await handler.run(req, res);
} catch (e) {
// handle the error
}
// do something with the - new and improved - req and res
return {
props: { user: req.user },
};
}
Using in other frameworks
splake
supports any frameworks that has the signature of (req, res)
.
Micro
const { send } = require("micro");
const handler = require("splake")();
handler
.use(middleware)
.get((req, res) => {
res.end("Hello World!");
})
.post((req, res) => {
send(res, 200, { hello: "world" });
});
module.exports = handler;
Node.js HTTP Server
const http = require("http");
const handler = require("splake")();
handler
.use(middleware)
.get((req, res) => {
res.end("Hello fish bois");
})
.post((req, res) => {
res.setHeader("content-type", "application/json");
res.end(JSON.stringify({ hello: "fish bois" }));
});
http.createServer(handler).listen(PORT);
Contributing
Please see my contributing.md.