Skip to content
This repository was archived by the owner on Feb 8, 2024. It is now read-only.

Commit b2cd0bd

Browse files
committed
Refactered flattening
1 parent 46f6271 commit b2cd0bd

2 files changed

Lines changed: 108 additions & 9 deletions

File tree

lib/flatten.js

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -3,16 +3,17 @@ function flattenize(routes, prefix, parent) {
33

44
Object.keys(routes.local).forEach(method => {
55
const localName = prefix === '/' ? '/' : `${prefix}/`
6-
list[localName] = {
7-
method,
8-
listeners: [].concat(
9-
parent.before,
10-
routes.before,
11-
routes.local[method],
12-
routes.after,
13-
parent.after
14-
),
6+
7+
if (!list[localName]) {
8+
list[localName] = {}
159
}
10+
list[localName][method] = [].concat(
11+
parent.before,
12+
routes.before,
13+
routes.local[method],
14+
routes.after,
15+
parent.after
16+
)
1617
})
1718

1819
Object.keys(routes.scoped).forEach(scope => {

lib/flatten.test.js

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,98 @@
1+
import test from 'ava'
2+
import { createRest, flattenRoutes } from './index'
3+
4+
/* eslint-disable no-shadow */
5+
6+
const get = () => {}
7+
const post = () => {}
8+
const put = () => {}
9+
const patch = () => {}
10+
const destroy = () => {}
11+
const before = () => {}
12+
const after = () => {}
13+
14+
const make = (method, listeners = []) => ({
15+
method, listeners,
16+
})
17+
18+
test('Empty', t => {
19+
t.deepEqual(
20+
flattenRoutes(createRest(r => {
21+
})),
22+
{
23+
}
24+
)
25+
})
26+
27+
test('Local methods', t => {
28+
t.deepEqual(
29+
flattenRoutes(createRest(r => {
30+
r.get(get)
31+
r.post(post)
32+
r.put(put)
33+
r.patch(patch)
34+
r.delete(destroy)
35+
})),
36+
{
37+
'/': {
38+
GET: [get],
39+
POST: [post],
40+
PUT: [put],
41+
PATCH: [patch],
42+
DELETE: [destroy],
43+
}
44+
}
45+
)
46+
})
47+
48+
test('Local and scoped methods', t => {
49+
t.deepEqual(
50+
flattenRoutes(createRest(r => {
51+
r.get(get)
52+
r.post(post)
53+
r.get('/name', get)
54+
r.post('/name', post)
55+
})),
56+
{
57+
'/': {
58+
GET: [get],
59+
POST: [post],
60+
},
61+
'/name/': {
62+
GET: [get],
63+
POST: [post],
64+
},
65+
}
66+
)
67+
})
68+
69+
test('Local, scoped methods and methods in scope', t => {
70+
t.deepEqual(
71+
flattenRoutes(createRest(r => {
72+
r.get(get)
73+
r.post(post)
74+
r.get('/name', get)
75+
r.post('name', post)
76+
r.scope('foo', r => {
77+
r.get(get)
78+
r.post('bar', post)
79+
})
80+
})),
81+
{
82+
'/': {
83+
GET: [get],
84+
POST: [post],
85+
},
86+
'/name/': {
87+
GET: [get],
88+
POST: [post],
89+
},
90+
'/foo/': {
91+
GET: [get],
92+
},
93+
'/foo/bar/': {
94+
POST: [post],
95+
},
96+
}
97+
)
98+
})

0 commit comments

Comments
 (0)