Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

fast-koa-router

Package Overview
Dependencies
Maintainers
1
Versions
13
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

fast-koa-router - npm Package Compare versions

Comparing version 1.0.1 to 1.1.0

.nyc_output/b340204d-7060-48d4-aadb-c310221489e6.json

2

.nyc_output/processinfo/index.json

@@ -1,1 +0,1 @@

{"processes":{"4be0f25a-2fe8-42c1-ac33-c887d44f53e1":{"parent":null,"children":[]}},"files":{"/Users/nikoskostoulas/dev/router/src/middleware.ts":["4be0f25a-2fe8-42c1-ac33-c887d44f53e1"],"/Users/nikoskostoulas/dev/router/src/router.ts":["4be0f25a-2fe8-42c1-ac33-c887d44f53e1"],"/Users/nikoskostoulas/dev/router/src/parse.ts":["4be0f25a-2fe8-42c1-ac33-c887d44f53e1"]},"externalIds":{}}
{"processes":{"b340204d-7060-48d4-aadb-c310221489e6":{"parent":null,"children":[]}},"files":{"/Users/nkostoulas/dev/fast-koa-router/src/middleware.ts":["b340204d-7060-48d4-aadb-c310221489e6"],"/Users/nkostoulas/dev/fast-koa-router/src/router.ts":["b340204d-7060-48d4-aadb-c310221489e6"],"/Users/nkostoulas/dev/fast-koa-router/src/parse.ts":["b340204d-7060-48d4-aadb-c310221489e6"]},"externalIds":{}}

@@ -6,3 +6,3 @@ export declare function parse(routes: any, path?: string, method?: any, parsedObj?: {}): {};

middleware: any;
_matchedRoute: string;
_matchedRoute: any;
params?: undefined;

@@ -9,0 +9,0 @@ } | {

@@ -19,6 +19,4 @@ "use strict";

if (Array.isArray(routes) || typeof routes === 'function') {
parsedObj[method] = {
[path]: { middleware: Array.isArray(routes) ? [...routes] : [routes] },
...parsedObj[method]
};
parsedObj[method] = parsedObj[method] || {};
parsedObj[method][path] = { middleware: Array.isArray(routes) ? [...routes] : [routes] };
return;

@@ -42,6 +40,8 @@ }

const pathVariableRegexp = /\/?(\:.*?)(?:\/|$)/g;
const starRegexp = /\/?(\*)(?:\/|$)/g;
function handlePathVariables(parsedObj) {
for (const routes of Object.values(parsedObj)) {
for (const [key, value] of Object.entries(routes)) {
const newKey = key.replace(pathVariableRegexp, (a, b) => a.replace(b, '_VAR_'));
let newKey = key.replace(pathVariableRegexp, (a, b) => a.replace(b, '_VAR_'));
newKey = newKey.replace(starRegexp, (a, b) => a.replace(b, '_STAR_'));
let iterator = routes;

@@ -52,3 +52,3 @@ const parts = newKey.split('/').filter(x => x);

for (const path of parts) {
iterator[`/${path}`] = { ...iterator[`/${path}`] };
iterator[`/${path}`] = iterator[`/${path}`] || {};
if (path === '_VAR_')

@@ -69,3 +69,5 @@ iterator[`/${path}`].paramName = oldParts[i].substring(1);

for (let [prefix, m] of Object.entries(prefixes).reverse()) {
let endsWithSlash = false;
if (prefix.endsWith('/')) {
endsWithSlash = true;
prefix = prefix.substr(0, prefix.length - 1);

@@ -80,2 +82,5 @@ }

if (newKey.indexOf(newPrefix) === 0 && value.middleware) {
if (endsWithSlash && newKey.length !== newPrefix.length && newKey[newPrefix.length] !== '/') {
continue;
}
value.middleware.unshift(...(Array.isArray(m) ? m : [m]));

@@ -102,3 +107,13 @@ }

let iterator = routes;
let middleware;
let lastMiddlewareRoute;
if (parts.length === 0 && iterator['/_STAR_']) {
iterator = iterator['/_STAR_'];
_matchedRoute += '/*';
}
for (const path of parts) {
if (iterator['/_STAR_']) {
lastMiddlewareRoute = _matchedRoute + '/*';
middleware = iterator['/_STAR_'].middleware;
}
if (iterator[`/${path}`]) {

@@ -113,7 +128,22 @@ _matchedRoute += `/${path}`;

}
else if (iterator['/_STAR_'] && iterator['/_STAR_'].middleware) {
_matchedRoute += '/*';
return { middleware: iterator['/_STAR_'].middleware, _matchedRoute };
}
else {
if (middleware) {
return { middleware, _matchedRoute: lastMiddlewareRoute };
}
return {};
}
}
return { middleware: iterator.middleware, params, _matchedRoute };
if (iterator.middleware) {
return { middleware: iterator.middleware, params, _matchedRoute };
}
else if (middleware) {
return { middleware, _matchedRoute: lastMiddlewareRoute };
}
else {
return {};
}
}

@@ -120,0 +150,0 @@ }

{
"name": "fast-koa-router",
"version": "1.0.1",
"version": "1.1.0",
"description": "",

@@ -5,0 +5,0 @@ "main": "build/middleware.js",

@@ -97,2 +97,26 @@ # Fast Koa Router

## Star symbol
Sometimes you need to have a fallback if no route matches with the requested url. You can have routes that end with a star eg:
```js
const routes = {
get: {
'/path': async function(ctx, next) {},
'/path/subpath': async function(ctx, next) {},
'/path/*': async function(ctx, next) {
ctx.body='Nothing in /path matches this request';
ctx.status=404;
},
'/*': async function(ctx, next) {
ctx.body='Nothing here';
ctx.status=404;
}
}
```
Note that star symboly is only supported after version 1.1.0 and only when used in the end of a route.
There is no reason to use it in prefix routes. Prefix routes will always match get, post, delete, patch, put urls if they use the same prefix.
## Policies

@@ -106,9 +130,9 @@

## Prefixes
Prefixes are also used to add middleware. Unlike policies they will only be executed if a matching
Prefixes are also used to add middleware. Unlike policies they will only be executed if a matching
get, post, put, delete or patch is found. They are convenient to add authentication or authorization in many paths that start with a prefix eg: /api/v1
Prefixes are executed after policies and before other middleware.
Note than both in prefix and policy middleware ctx.params and ctx._matchedRoute are available.
Note than both in prefix and policy middleware ctx.params and ctx.\_matchedRoute are available.
## Fast

@@ -115,0 +139,0 @@

@@ -75,2 +75,49 @@ import * as assert from 'assert';

it('should not add if prefix ends with /', function() {
assert.deepEqual(
getPathMethod(
handlePathVariables(
addPrefixMiddleware(
parse({
get: {
'/path': ['middleware']
}
}),
{ '/pa/': 'prefix' }
)
),
'/path',
'get'
),
{
_matchedRoute: '/path',
middleware: ['middleware']
}
);
});
// tslint:disable-next-line: quotemark
it("should add prefix if it doesn't end with /", function() {
assert.deepEqual(
getPathMethod(
handlePathVariables(
addPrefixMiddleware(
parse({
get: {
'/path': ['middleware']
}
}),
{ '/pa': 'prefix' }
)
),
'/path',
'get'
),
{
_matchedRoute: '/path',
middleware: ['prefix', 'middleware']
}
);
});
it('should add prefix middleware to all matching routes', function() {

@@ -101,2 +148,65 @@ snapshot(

});
describe('route that matches every path', function() {
it('should fallback to star routes', function() {
let routes = handlePathVariables(
addPrefixMiddleware(
parse({
get: {
'/path': ['middleware'],
'/path/1': ['one'],
'/path/1/3/foo': ['foo'],
'/path/*': ['star'],
'/*': ['initialStar']
}
}),
{ '/path': 'prefix' }
)
);
assert.deepEqual(getPathMethod(routes, '/path/1', 'get'), {
_matchedRoute: '/path/1',
middleware: ['prefix', 'one']
});
assert.deepEqual(getPathMethod(routes, '/path/foo', 'get'), {
_matchedRoute: '/path/*',
middleware: ['prefix', 'star']
});
assert.deepEqual(getPathMethod(routes, '/path/1/3', 'get'), {
_matchedRoute: '/path/*',
middleware: ['prefix', 'star']
});
assert.deepEqual(getPathMethod(routes, '/path/1/2', 'get'), {
_matchedRoute: '/path/*',
middleware: ['prefix', 'star']
});
assert.deepEqual(getPathMethod(routes, '/', 'get'), {
_matchedRoute: '/*',
middleware: ['initialStar'],
params: {}
});
});
it('should fallback to star routes', function() {
let routes = handlePathVariables(
addPrefixMiddleware(
parse({
get: {
'/path': ['middleware'],
'/path/1': ['one'],
'/path/1/3/foo': ['foo'],
'/path2/1/3/foo': ['foo'],
'/path/*': ['star']
}
}),
{ '/path': 'prefix' }
)
);
assert.deepEqual(getPathMethod(routes, '/path2/1', 'get'), {});
});
});
});

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc