all repos — litestore @ 016fcfdf3f28f338c27228dab000f2dd6a585272

A minimalist nosql document store.

Fixed middleware execution.
h3rald h3rald@h3rald.com
Fri, 06 Mar 2020 15:04:27 +0100
commit

016fcfdf3f28f338c27228dab000f2dd6a585272

parent

bd2fa1c09df1591de45af167a5d4587b1b0cc578

M .gitignore.gitignore

@@ -16,4 +16,6 @@ LiteStore_UserGuide.htm

jester_integration js *_backup -config.json +./config.json +*.db-shm +*.db-wal
M src/admin/md/litestore_js_object.mdsrc/admin/md/global_js_objects.md

@@ -1,8 +1,8 @@

-## LiteStore Global Object +## Global JavaScript Objects -When creating JavaScript handlers for custom resources, you can use a special **LiteStore** global object to access the HTTP request to the resource, modify the HTTP response, and also access other LiteStore resources. +When creating JavaScript handlers for middleware, you can use some special $-prefixed global objects to access the HTTP request to the resource, the HTTP response, and also access other LiteStore resources. -### LiteStore.request +### $req The current HTTP request sent to access the current resource.

@@ -17,7 +17,7 @@ <dt>headers: object</dt>

<dd>An object containing the request headers, as keys and values.</dd> </dl> -### LiteStore.response +### $res The HTTP response to return to the client.
A src/litestorepkg/examples/system/config.json

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

+{ + "settings": { + "log": "warn", + "port": 9200 + }, + "resources": { + "/docs/vehicles/*": { + "GET": { + "middleware": ["validate", "log"] + }, + "HEAD": { + "middleware": ["validate", "log"] + }, + "POST": { + "allowed": false + }, + "PATCH": { + "auth": ["admin:vehicles"], + "middleware": ["validate", "log"] + }, + "PUT": { + "middleware": ["validate", "log"] + }, + "DELETE": { + "auth": ["admin:vehicles"], + "middleware": ["validate", "log"] + } + }, + "/docs/logs/*": { + "GET": { + "auth": ["admin:server"] + }, + "POST": { + "allowed": false + }, + "PUT": { + "allowed": false + }, + "PATCH": { + "allowed": false + }, + "DELETE": { + "allowed": false + } + } + }, + "signature": "\n-----BEGIN CERTIFICATE-----\n<certificate text goes here>\n-----END CERTIFICATE-----\n" +}
M src/litestorepkg/examples/system/middleware/log.jssrc/litestorepkg/examples/system/middleware/log.js

@@ -1,9 +1,10 @@

(function(){ var doc = { - sub: $req.jwt.claims && $req.jwt.claims.sub || null, + user: $req.jwt.claims && $req.jwt.claims.sub || null, agent: $req.headers['user-agent'], language: $req.headers['accept-language'] && $req.headers['accept-language'].replace(/,.+$/, ''), path: $req.path, + existing: !!$ctx.existing, method: $req.method, timestamp: Date.now() }
M src/litestorepkg/examples/system/middleware/validate.jssrc/litestorepkg/examples/system/middleware/validate.js

@@ -1,11 +1,12 @@

-(function () { - var id = $req.path.replace(/^\/docs\//, ''); +(function() { + var id = $req.path.replace(/^\/docs\//, ""); var valid = /[A-Z]{2}[0-9]{3}[A-Z]{2}/; if (!id.match(valid)) { $res.content = { - error: 'Invalid number plate' + error: "Invalid number plate" }; $res.code = 400; return true; } -}())+ $ctx.existing = !!($store.get("docs", id).code == 200); +})();
M src/litestorepkg/lib/api_v6.nimsrc/litestorepkg/lib/api_v6.nim

@@ -1063,7 +1063,6 @@ var currentPaths = ""

for p in ancestors: currentPath &= "/" & p currentPaths = currentPath & "/*" - echo currentPaths if LS.config["resources"].hasKey(currentPaths) and LS.config["resources"][currentPaths].hasKey(meth) and LS.config["resources"][currentPaths][meth].hasKey("middleware"): let mw = LS.config["resources"][currentPaths][meth]["middleware"] if (mw.kind == JArray):

@@ -1077,11 +1076,11 @@ result.add m.getStr

proc execute*(req: var LSRequest, LS: LiteStore, resource, id: string): LSResponse = let middleware = getMiddlewareSeq(resource, id, $req.reqMethod) - LOG.debug("Middleware: ", middleware); + LOG.debug("Middleware: " & middleware.join(" -> ")); if middleware.len == 0: return route(req, LS, resource, id) var jReq = $(%* req) - LOG.debug("Request: ", jReq) + LOG.debug("Request: " & jReq) var jRes = """{ "code": 200, "content": {},

@@ -1099,32 +1098,19 @@ var ctx = duk_create_heap_default()

duk_console_init(ctx) duk_print_alert_init(ctx) LS.registerStoreApi(ctx, resource, id) - if ctx.duk_peval_string("JSON.parse('$1');" % jReq) != 0: + if ctx.duk_peval_string("($1)" % $jReq) != 0: return jError(ctx) discard ctx.duk_put_global_string("$req") - if ctx.duk_peval_string("JSON.parse('$1');" % jRes.replace("\n", "")) != 0: + if ctx.duk_peval_string("($1)" % $jRes) != 0: return jError(ctx) discard ctx.duk_put_global_string("$res") - if ctx.duk_peval_string("JSON.parse('$1');" % context) != 0: + if ctx.duk_peval_string("($1)" % $context) != 0: return jError(ctx) discard ctx.duk_put_global_string("$ctx") # Middleware-specific functions - #let fNext: DTCFunction = (proc (ctx: DTContext): cint{.stdcall.} = - # return ctx.duk_peval_string("__next__ = true;") - #) - #discard duk_push_c_function(ctx, fNext, 0) - #discard ctx.duk_put_global_string("$next") var i = 0 - #ctx.duk_push_boolean(0) - #discard ctx.duk_put_global_string("__next__") var abort = 0 while abort != 1 and i < middleware.len: - #if ctx.duk_peval_string("__next__") != 0: - # return jError(ctx) - #next = ctx.duk_get_boolean(-1) - #echo next - #if next == 0: - # abort = 1 let code = LS.getMiddleware(middleware[i]) LOG.debug("Evaluating middleware '$1'" % middleware[i]) if ctx.duk_peval_string(code) != 0:
M src/litestorepkg/lib/core.nimsrc/litestorepkg/lib/core.nim

@@ -99,7 +99,7 @@ LOG.debug("Registering custom functions...")

discard create_function(cast[PSqlite3](result.db), "rank", -1, SQLITE_ANY, cast[pointer](SQLITE_DETERMINISTIC), okapi_bm25f_kb, nil, nil) LOG.debug("Executing PRAGMAs...") - discard result.db.tryExec("PRAGMA locking_mode = exclusive".sql) + discard result.db.tryExec("PRAGMA journal_mode = WAL".sql) discard result.db.tryExec("PRAGMA page_size = 4096".sql) discard result.db.tryExec("PRAGMA cache_size = 10000".sql) discard result.db.tryExec("PRAGMA foreign_keys = ON".sql)
M src/litestorepkg/lib/types.nimsrc/litestorepkg/lib/types.nim

@@ -185,7 +185,7 @@ proc newLSRequest*(req: JsonNode): LSRequest =

result.reqMethod = httpMethod(req["method"].getStr) result.headers = newHttpHeaders() for k, v in req["headers"].pairs: - result.headers[k] = $v + result.headers[k] = v.getStr let protocol = req["protocol"].getStr let parts = protocol.split("/") let version = parts[1].split(".")

@@ -196,7 +196,7 @@ result.url.port = req["port"].getStr

result.url.path = req["path"].getStr result.url.query = req["query"].getStr result.hostname = req["hostname"].getStr - result.body = $req["content"] + result.body = req["content"].getStr proc newLSRequest*(req: Request): LSRequest = result.reqMethod = req.reqMethod