Skip to content

Commit 815e816

Browse files
🚸 Update HTTP operation sort order (#59)
1 parent f9774de commit 815e816

File tree

2 files changed

+46
-4
lines changed

2 files changed

+46
-4
lines changed

‎src/test/providers/endpointTreeProvider.test.ts‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,33 @@ suite("EndpointTreeProvider", () => {
159159
)
160160
})
161161

162+
test("routes are sorted by method priority then path", () => {
163+
const app = makeApp("app", "main.py")
164+
app.routes = [
165+
makeRoute("DELETE", "/users"),
166+
makeRoute("GET", "/users"),
167+
makeRoute("POST", "/items"),
168+
makeRoute("PATCH", "/users"),
169+
makeRoute("GET", "/items"),
170+
makeRoute("POST", "/users"),
171+
makeRoute("PUT", "/users"),
172+
]
173+
const p = new EndpointTreeProvider([app])
174+
const children = p.getChildren(p.getChildren()[0])
175+
const labels = children.map((c) =>
176+
c.type === "route" ? getRouteLabel(c.route) : "",
177+
)
178+
assert.deepStrictEqual(labels, [
179+
"GET /items",
180+
"GET /users",
181+
"POST /items",
182+
"POST /users",
183+
"PUT /users",
184+
"PATCH /users",
185+
"DELETE /users",
186+
])
187+
})
188+
162189
test("getChildren returns routes for router", () => {
163190
const roots = provider.getChildren()
164191
const app = roots[0]

‎src/vscode/endpointTreeProvider.ts‎

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,17 @@ export type EndpointTreeItem =
2222
| { type: "route"; route: RouteDefinition }
2323
| { type: "message"; text: string }
2424

25+
const METHOD_ORDER: Record<RouteMethod, number> = {
26+
GET: 0,
27+
POST: 1,
28+
PUT: 2,
29+
PATCH: 3,
30+
DELETE: 4,
31+
OPTIONS: 5,
32+
HEAD: 6,
33+
WEBSOCKET: 7,
34+
}
35+
2536
export const METHOD_ICONS: Record<RouteMethod, string> = {
2637
GET: "arrow-right",
2738
POST: "plus",
@@ -92,11 +103,15 @@ function sortedChildren(
92103
),
93104
...routes
94105
.map((route) => ({ type: "route" as const, route }))
95-
.sort((a, b) =>
96-
getRouteLabel(a.route)
106+
.sort((a, b) => {
107+
// If negative, a comes first. If positive, b comes first. If 0, sort by label.
108+
const methodOrder =
109+
METHOD_ORDER[a.route.method] - METHOD_ORDER[b.route.method]
110+
if (methodOrder !== 0) return methodOrder
111+
return getRouteLabel(a.route)
97112
.toLowerCase()
98-
.localeCompare(getRouteLabel(b.route).toLowerCase()),
99-
),
113+
.localeCompare(getRouteLabel(b.route).toLowerCase())
114+
}),
100115
]
101116
}
102117

0 commit comments

Comments
 (0)