QueryHandler: Added new handy query handler middleware

master
Jonatan Nilsson 2021-10-10 20:38:12 +00:00
parent e5ca7e5d74
commit 89c96e2ad4
3 changed files with 36 additions and 0 deletions

View File

@ -1,4 +1,5 @@
import http from 'http'
import { URL } from 'url'
import stream from 'stream'
/**
@ -50,6 +51,12 @@ function assertIsHandler(handler, name) {
}
}
export function QueryHandler() {
return function(ctx) {
ctx.query = (new URL(ctx.req.url, 'http://localhost')).searchParams
}
}
export class FlaskaRouter {
constructor() {
this.root = new Branch()
@ -379,6 +386,7 @@ export class Flaska {
search: search,
state: {},
status: 200,
query: new Map(),
body: null,
type: null,
length: null,

View File

@ -151,6 +151,10 @@ t.describe('#requestStart()', function() {
assert.strictEqual(ctx.type, null)
assert.strictEqual(ctx.length, null)
assert.strictEqual(ctx.log, assertLog)
assert.ok(ctx.query)
assert.ok(ctx.query.get)
assert.ok(ctx.query.set)
assert.ok(ctx.query.delete)
cb()
} catch (err) { cb(err) }
}

24
test/middlewares.test.mjs Normal file
View File

@ -0,0 +1,24 @@
import { Eltro as t, assert} from 'eltro'
import { QueryHandler } from '../flaska.mjs'
t.describe('#QueryHandler()', function() {
let queryHandler = QueryHandler()
t.test('should return a handler', function() {
assert.strictEqual(typeof(queryHandler), 'function')
})
t.test('should support separating query from request url', function() {
const assertItem1 = 'safdsfdsag'
const assertItem2 = 'hello%20world'
const ctx = {
req: {
url: `/some/path?item1=${assertItem1}&ITEM2=${assertItem2}`
}
}
queryHandler(ctx)
assert.strictEqual(ctx.query.get('item1'), assertItem1)
assert.strictEqual(ctx.query.get('ITEM2'), 'hello world')
})
})