Skip to content

Commit c09cfb5

Browse files
committed
FEAT: Add express-like support for params (or query)
1 parent b2a1d51 commit c09cfb5

File tree

4 files changed

+14
-6
lines changed

4 files changed

+14
-6
lines changed

README.md

+5-1
Original file line numberDiff line numberDiff line change
@@ -23,11 +23,15 @@ const AuthHandler = Controller("/auth", {
2323
},
2424
async "GET /[id]/info"(req, res) {
2525
res.send("Info for " + req.query.id)
26+
},
27+
// Like Express
28+
async "GET /:id/info/:slug"(req, res) {
29+
res.send("Info for " + req.query.id)
2630
}
2731
})
2832
```
2933

3034
#### Explanation
31-
When adding a handler/method, it should start with an HTTP verb, followed by a space, and a url to handle (with or without query params using square brackets).
35+
When adding a handler/method, it should start with an HTTP verb, followed by a space, and a url to handle (with or without query params using square brackets, or like Express, by placing `:` before).
3236

3337
Sending, for example, a POST request that would be handled by a GET handler, will send a `405` status code

lib/index.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -68,9 +68,10 @@ function Controller(path, paths) {
6868
var finalHandler = [];
6969
var finalQuery = {};
7070
handleParts.forEach(function (handlePart, i) {
71-
if (handlePart.startsWith("[") && handlePart.endsWith("]")) {
71+
if ((handlePart.startsWith("[") && handlePart.endsWith("]")) ||
72+
handlePart.startsWith(":")) {
7273
hasHandlers = true;
73-
var withoutBrackets = handlePart.replace(/\[|\]/g, "");
74+
var withoutBrackets = handlePart.replace(/\[|\]|\:/g, "");
7475
finalQuery[withoutBrackets] = urlParts[i];
7576
finalHandler.push(urlParts[i]);
7677
}

package.json

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "next-rest-controller",
3-
"version": "0.0.5",
3+
"version": "0.0.6",
44
"description": "A REST helper for Next apis",
55
"main": "lib/index.js",
66
"repository": "https://github.com/atomic-state/rest-next",

src/index.ts

+5-2
Original file line numberDiff line numberDiff line change
@@ -29,9 +29,12 @@ export function Controller(path: string, paths: ControllerMethods = {}) {
2929
let finalQuery: any = {}
3030

3131
handleParts.forEach((handlePart, i) => {
32-
if (handlePart.startsWith("[") && handlePart.endsWith("]")) {
32+
if (
33+
(handlePart.startsWith("[") && handlePart.endsWith("]")) ||
34+
handlePart.startsWith(":")
35+
) {
3336
hasHandlers = true
34-
const withoutBrackets = handlePart.replace(/\[|\]/g, "")
37+
const withoutBrackets = handlePart.replace(/\[|\]|\:/g, "")
3538

3639
finalQuery[withoutBrackets] = urlParts[i]
3740

0 commit comments

Comments
 (0)