mithril-vndb/request/tests/test-request.js
Isiah Meadows 58f1c74394
Streamline route/request path handling and split params + body in requests (#2361)
Fixes #2360
Fixes #1138
Fixes #1788 a little less hackishly
Probably fixes a few other issues I'm not aware of.

This more or less goes with @lhorie's comment here, just with a minor name
change from `query` to `params`:

https://github.com/MithrilJS/mithril.js/issues/1138#issuecomment-231363395

Specifically, here's what this patch entails:

- I changed `data` and `useBody` to `params` and `body` in `m.request`.
  Migration is trivial: just use `params` or `body` depending on which you
  intend to send. Most servers do actually care where the data goes, so you can
  generally pretty easily translate this accordingly. If you *really* need the
  old behavior, pass the old value in `params` and if `method === "GET"` or
  `method === "TRACE"`, also in `body`.
- I opened up all methods to have request bodies.
- I fixed `m.parseQueryString` to prefer later values over earlier values and
  to ensure that objects and arrays are persisted across both hash and query
  param parsing. That method also accepts an existing key/value map to append
  to, to simplify deduplication.
- I normalized path interpolation to be identical between routes and requests.
- I no longer include interpolated values in query strings. If you need to
  duplicate values again, rename the interpolation to be a distinct property
  and pass the value you want to duplicate as it.
- I converted `m.route` to use pre-compiled routes instead of its existing
  system of dynamic runtime checking. This shouldn't have a major effect on
  performance short-term, but it'll ease the migration to built-in userland
  components and make it a little easier to reconcile. It'll also come handy
  for large numbers of routes.
- I added support for matching routes like `"/:file.:ext"` or
  `"/:lang-:region"`, giving each defined semantics.
- I added support for matching against routes with static query strings, such
  as `"/edit?type=image": { ... }`.
- I'm throwing a few new informative errors.
- And I've updated the docs accordingly.

I also made a few drive-by edits:

- I fixed a bug in the `Stream.HALT` warning where it warned all but the first
  usage when the intent was to warn only on first use.
- Some of the tests were erroneously using `Stream.HALT` when they should've
  been using `Stream.SKIP`. I've fixed the tests to only test that
  `Stream.HALT === Stream.SKIP` and that it only warns on first use.
- The `m.request` and `m.jsonp` docs signatures were improved to more clearly
  explain how `m.request(url, options?)` and `m.jsonp(url, options?)` translate
  to `m.request(options)` and `m.jsonp(options)` respectively.

-----

There is some justification to these changes:

- In general, it matters surprisingly more than you would expect how things
  translate to HTTP requests. So the comment there suggesting a thing that
  papers over the difference has led to plenty of confusion in both Gitter and
  in GitHub issues.

- A lot of servers expect a GET with a body and no parameters, and leaving
  `m.request` open to working with that makes it much more flexible.

- Sometimes, servers expect a POST with query parameters *instead* of a JSON
  object. I've seen this quite a bit, even with more popular REST APIs like
  Stack Overflow's.

- I've encountered a few servers that expect both parameters and a body, each
  with distinct semantic meaning, so the separation makes it much easier to
  translate into a request.

- Most of the time, path segments are treated individually, and URL-escaping
  the contents is much less error-prone. It also avoids being potentially
  lossy, and when the variable in question isn't trusted, escaping the path
  segment enables you to pass it through the URL and not risk being redirected
  to unexpected locations, avoiding some risks of vulnerabilities and client
  side crashes.

If you really don't care how the template and parameters translate to an
eventual URL, just pass the same object for the `params` and `body` and use
`:param...` for each segment. Either way, the more explicit nature should help
a lot in making the intent clearer, whether you care or not.
2019-05-29 09:28:40 -04:00

641 lines
19 KiB
JavaScript

"use strict"
var o = require("../../ospec/ospec")
var callAsync = require("../../test-utils/callAsync")
var xhrMock = require("../../test-utils/xhrMock")
var Request = require("../../request/request")
var Promise = require("../../promise/promise")
o.spec("xhr", function() {
var mock, xhr, complete
o.beforeEach(function() {
mock = xhrMock()
var requestService = Request(mock, Promise)
xhr = requestService.request
complete = o.spy()
requestService.setCompletionCallback(complete)
})
o.spec("success", function() {
o("works via GET", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: JSON.stringify({a: 1})}
}
})
xhr({method: "GET", url: "/item"}).then(function(data) {
o(data).deepEquals({a: 1})
}).then(function() {
done()
})
})
o("implicit GET method", function(done){
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: JSON.stringify({a: 1})}
}
})
xhr({url: "/item"}).then(function(data) {
o(data).deepEquals({a: 1})
}).then(function() {
done()
})
})
o("first argument can be a string aliasing url property", function(done){
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: JSON.stringify({a: 1})}
}
})
xhr("/item").then(function(data) {
o(data).deepEquals({a: 1})
}).then(function() {
done()
})
})
o("works via POST", function(done) {
mock.$defineRoutes({
"POST /item": function() {
return {status: 200, responseText: JSON.stringify({a: 1})}
}
})
xhr({method: "POST", url: "/item"}).then(function(data) {
o(data).deepEquals({a: 1})
}).then(done)
})
o("first argument can act as URI with second argument providing options", function(done) {
mock.$defineRoutes({
"POST /item": function() {
return {status: 200, responseText: JSON.stringify({a: 1})}
}
})
xhr("/item", {method: "POST"}).then(function(data) {
o(data).deepEquals({a: 1})
}).then(done)
})
o("works w/ parameterized data via GET", function(done) {
mock.$defineRoutes({
"GET /item": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.query})}
}
})
xhr({method: "GET", url: "/item", params: {x: "y"}}).then(function(data) {
o(data).deepEquals({a: "?x=y"})
}).then(done)
})
o("works w/ parameterized data via POST", function(done) {
mock.$defineRoutes({
"POST /item": function(request) {
return {status: 200, responseText: JSON.stringify({a: JSON.parse(request.body)})}
}
})
xhr({method: "POST", url: "/item", body: {x: "y"}}).then(function(data) {
o(data).deepEquals({a: {x: "y"}})
}).then(done)
})
o("works w/ parameterized data containing colon via GET", function(done) {
mock.$defineRoutes({
"GET /item": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.query})}
}
})
xhr({method: "GET", url: "/item", params: {x: ":y"}}).then(function(data) {
o(data).deepEquals({a: "?x=%3Ay"})
}).then(done)
})
o("works w/ parameterized data containing colon via POST", function(done) {
mock.$defineRoutes({
"POST /item": function(request) {
return {status: 200, responseText: JSON.stringify({a: JSON.parse(request.body)})}
}
})
xhr({method: "POST", url: "/item", body: {x: ":y"}}).then(function(data) {
o(data).deepEquals({a: {x: ":y"}})
}).then(done)
})
o("works w/ parameterized url via GET", function(done) {
mock.$defineRoutes({
"GET /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: request.body})}
}
})
xhr({method: "GET", url: "/item/:x", params: {x: "y"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: {}, c: null})
}).then(done)
})
o("works w/ parameterized url via POST", function(done) {
mock.$defineRoutes({
"POST /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: request.body})}
}
})
xhr({method: "POST", url: "/item/:x", params: {x: "y"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: {}, c: null})
}).then(done)
})
o("works w/ parameterized url + body via GET", function(done) {
mock.$defineRoutes({
"GET /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: JSON.parse(request.body)})}
}
})
xhr({method: "GET", url: "/item/:x", params: {x: "y"}, body: {a: "b"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: {}, c: {a: "b"}})
}).then(done)
})
o("works w/ parameterized url + body via POST", function(done) {
mock.$defineRoutes({
"POST /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: JSON.parse(request.body)})}
}
})
xhr({method: "POST", url: "/item/:x", params: {x: "y"}, body: {a: "b"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: {}, c: {a: "b"}})
}).then(done)
})
o("works w/ parameterized url + query via GET", function(done) {
mock.$defineRoutes({
"GET /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: request.body})}
}
})
xhr({method: "GET", url: "/item/:x", params: {x: "y", q: "term"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: "?q=term", c: null})
}).then(done)
})
o("works w/ parameterized url + query via POST", function(done) {
mock.$defineRoutes({
"POST /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: request.body})}
}
})
xhr({method: "POST", url: "/item/:x", params: {x: "y", q: "term"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: "?q=term", c: null})
}).then(done)
})
o("works w/ parameterized url + query + body via GET", function(done) {
mock.$defineRoutes({
"GET /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: JSON.parse(request.body)})}
}
})
xhr({method: "GET", url: "/item/:x", params: {x: "y", q: "term"}, body: {a: "b"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: "?q=term", c: {a: "b"}})
}).then(done)
})
o("works w/ parameterized url + query + body via POST", function(done) {
mock.$defineRoutes({
"POST /item/y": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: request.query, c: JSON.parse(request.body)})}
}
})
xhr({method: "POST", url: "/item/:x", params: {x: "y", q: "term"}, body: {a: "b"}}).then(function(data) {
o(data).deepEquals({a: "/item/y", b: "?q=term", c: {a: "b"}})
}).then(done)
})
o("works w/ array", function(done) {
mock.$defineRoutes({
"POST /items": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url, b: JSON.parse(request.body)})}
}
})
xhr({method: "POST", url: "/items", body: [{x: "y"}]}).then(function(data) {
o(data).deepEquals({a: "/items", b: [{x: "y"}]})
}).then(done)
})
o("ignores unresolved parameter via GET", function(done) {
mock.$defineRoutes({
"GET /item/:x": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url})}
}
})
xhr({method: "GET", url: "/item/:x"}).then(function(data) {
o(data).deepEquals({a: "/item/:x"})
}).then(done)
})
o("ignores unresolved parameter via POST", function(done) {
mock.$defineRoutes({
"GET /item/:x": function(request) {
return {status: 200, responseText: JSON.stringify({a: request.url})}
}
})
xhr({method: "GET", url: "/item/:x"}).then(function(data) {
o(data).deepEquals({a: "/item/:x"})
}).then(done)
})
o("type parameter works for Array responses", function(done) {
var Entity = function(args) {
return {_id: args.id}
}
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: JSON.stringify([{id: 1}, {id: 2}, {id: 3}])}
}
})
xhr({method: "GET", url: "/item", type: Entity}).then(function(data) {
o(data).deepEquals([{_id: 1}, {_id: 2}, {_id: 3}])
}).then(done)
})
o("type parameter works for Object responses", function(done) {
var Entity = function(args) {
return {_id: args.id}
}
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: JSON.stringify({id: 1})}
}
})
xhr({method: "GET", url: "/item", type: Entity}).then(function(data) {
o(data).deepEquals({_id: 1})
}).then(done)
})
o("serialize parameter works in GET", function(done) {
var serialize = function(data) {
return "id=" + data.id
}
mock.$defineRoutes({
"GET /item": function(request) {
return {status: 200, responseText: JSON.stringify({body: request.query})}
}
})
xhr({method: "GET", url: "/item", serialize: serialize, params: {id: 1}}).then(function(data) {
o(data.body).equals("?id=1")
}).then(done)
})
o("serialize parameter works in POST", function(done) {
var serialize = function(data) {
return "id=" + data.id
}
mock.$defineRoutes({
"POST /item": function(request) {
return {status: 200, responseText: JSON.stringify({body: request.body})}
}
})
xhr({method: "POST", url: "/item", serialize: serialize, body: {id: 1}}).then(function(data) {
o(data.body).equals("id=1")
}).then(done)
})
o("deserialize parameter works in GET", function(done) {
var deserialize = function(data) {
return data
}
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: JSON.stringify({test: 123})}
}
})
xhr({method: "GET", url: "/item", deserialize: deserialize}).then(function(data) {
o(data).equals("{\"test\":123}")
}).then(done)
})
o("deserialize parameter works in POST", function(done) {
var deserialize = function(data) {
return data
}
mock.$defineRoutes({
"POST /item": function() {
return {status: 200, responseText: JSON.stringify({test: 123})}
}
})
xhr({method: "POST", url: "/item", deserialize: deserialize}).then(function(data) {
o(data).equals("{\"test\":123}")
}).then(done)
})
o("extract parameter works in GET", function(done) {
var extract = function() {
return JSON.stringify({test: 123})
}
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: ""}
}
})
xhr({method: "GET", url: "/item", extract: extract}).then(function(data) {
o(data).equals("{\"test\":123}")
}).then(done)
})
o("extract parameter works in POST", function(done) {
var extract = function() {
return JSON.stringify({test: 123})
}
mock.$defineRoutes({
"POST /item": function() {
return {status: 200, responseText: ""}
}
})
xhr({method: "POST", url: "/item", extract: extract}).then(function(data) {
o(data).equals("{\"test\":123}")
}).then(done)
})
o("ignores deserialize if extract is defined", function(done) {
var extract = function(data) {
return data.status
}
var deserialize = o.spy()
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: ""}
}
})
xhr({method: "GET", url: "/item", extract: extract, deserialize: deserialize}).then(function(data) {
o(data).equals(200)
}).then(function() {
o(deserialize.callCount).equals(0)
}).then(done)
})
o("config parameter works", function(done) {
mock.$defineRoutes({
"POST /item": function() {
return {status: 200, responseText: ""}
}
})
xhr({method: "POST", url: "/item", config: config}).then(done)
function config(xhr) {
o(typeof xhr.setRequestHeader).equals("function")
o(typeof xhr.open).equals("function")
o(typeof xhr.send).equals("function")
}
})
o("requests don't block each other", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: "[]"}
}
})
xhr("/item").then(function() {
return xhr("/item")
})
xhr("/item").then(function() {
return xhr("/item")
})
setTimeout(function() {
o(complete.callCount).equals(4)
done()
}, 20)
})
o("requests trigger finally once with a chained then", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: "[]"}
}
})
var promise = xhr("/item")
promise.then(function() {}).then(function() {})
promise.then(function() {}).then(function() {})
setTimeout(function() {
o(complete.callCount).equals(1)
done()
}, 20)
})
o("requests does not trigger finally when background: true", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: "[]"}
}
})
xhr("/item", {background: true}).then(function() {})
setTimeout(function() {
o(complete.callCount).equals(0)
done()
}, 20)
})
o("headers are set when header arg passed", function(done) {
mock.$defineRoutes({
"POST /item": function() {
return {status: 200, responseText: ""}
}
})
xhr({method: "POST", url: "/item", config: config, headers: {"Custom-Header": "Value"}}).then(done)
function config(xhr) {
o(xhr.getRequestHeader("Custom-Header")).equals("Value")
}
})
o("headers are with higher precedence than default headers", function(done) {
mock.$defineRoutes({
"POST /item": function() {
return {status: 200, responseText: ""}
}
})
xhr({method: "POST", url: "/item", config: config, headers: {"Content-Type": "Value"}}).then(done)
function config(xhr) {
o(xhr.getRequestHeader("Content-Type")).equals("Value")
}
})
o("json headers are set to the correct default value", function(done) {
mock.$defineRoutes({
"POST /item": function() {
return {status: 200, responseText: ""}
}
})
xhr({method: "POST", url: "/item", config: config}).then(done)
function config(xhr) {
o(xhr.getRequestHeader("Content-Type")).equals("application/json; charset=utf-8")
o(xhr.getRequestHeader("Accept")).equals("application/json, text/*")
}
})
o("doesn't fail on abort", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: JSON.stringify({a: 1})}
}
})
var failed = false
var resolved = false
function handleAbort(xhr) {
var onreadystatechange = xhr.onreadystatechange // probably not set yet
var testonreadystatechange = function() {
onreadystatechange.call(xhr)
setTimeout(function() { // allow promises to (not) resolve first
o(failed).equals(false)
o(resolved).equals(false)
done()
}, 0)
}
Object.defineProperty(xhr, "onreadystatechange", {
set: function(val) { onreadystatechange = val },
get: function() { return testonreadystatechange }
})
xhr.abort()
}
xhr({method: "GET", url: "/item", config: handleAbort}).catch(function() {
failed = true
})
.then(function() {
resolved = true
})
})
o("doesn't fail on file:// status 0", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 0, responseText: JSON.stringify({a: 1})}
}
})
var failed = false
xhr({method: "GET", url: "file:///item"}).catch(function() {
failed = true
}).then(function(data) {
o(failed).equals(false)
o(data).deepEquals({a: 1})
}).then(function() {
done()
})
})
o("set timeout to xhr instance", function() {
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: ""}
}
})
return xhr({
method: "GET", url: "/item",
timeout: 42,
config: function(xhr) {
o(xhr.timeout).equals(42)
}
})
})
o("set responseType to xhr instance", function() {
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: ""}
}
})
return xhr({
method: "GET", url: "/item",
responseType: "blob",
config: function(xhr) {
o(xhr.responseType).equals("blob")
}
})
})
/*o("data maintains after interpolate", function() {
mock.$defineRoutes({
"PUT /items/:x": function() {
return {status: 200, responseText: ""}
}
})
var data = {x: 1, y: 2}
var dataCopy = Object.assign({}, data);
xhr({method: "PUT", url: "/items/:x", data})
o(data).deepEquals(dataCopy)
})*/
})
o.spec("failure", function() {
o("rejects on server error", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 500, responseText: JSON.stringify({error: "error"})}
}
})
xhr({method: "GET", url: "/item"}).catch(function(e) {
o(e instanceof Error).equals(true)
o(e.message).equals(JSON.stringify({error: "error"}))
o(e.code).equals(500)
}).then(done)
})
o("adds response to Error", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 500, responseText: JSON.stringify({message: "error", stack: "error on line 1"})}
}
})
xhr({method: "GET", url: "/item"}).catch(function(e) {
o(e instanceof Error).equals(true)
o(e.response.message).equals("error")
o(e.response.stack).equals("error on line 1")
}).then(done)
})
o("rejects on non-JSON server error", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 500, responseText: "error"}
}
})
xhr({method: "GET", url: "/item"}).catch(function(e) {
o(e.message).equals("Invalid JSON: error")
}).then(done)
})
o("triggers all branched catches upon rejection", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 500, responseText: "error"}
}
})
var request = xhr({method: "GET", url: "/item"})
var then = o.spy()
var catch1 = o.spy()
var catch2 = o.spy()
var catch3 = o.spy()
request.catch(catch1)
request.then(then, catch2)
request.then(then).catch(catch3)
callAsync(function() {
callAsync(function() {
o(catch1.callCount).equals(1)
o(then.callCount).equals(0)
o(catch2.callCount).equals(1)
o(catch3.callCount).equals(1)
done()
})
})
})
o("rejects on cors-like error", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 0}
}
})
xhr({method: "GET", url: "/item"}).catch(function(e) {
o(e instanceof Error).equals(true)
}).then(done)
})
o("does not reject on status error code when extract provided", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 500, responseText: JSON.stringify({message: "error"})}
}
})
xhr({
method: "GET", url: "/item",
extract: function(xhr) {return JSON.parse(xhr.responseText)}
}).then(function(data) {
o(data.message).equals("error")
done()
})
})
o("rejects on error in extract", function(done) {
mock.$defineRoutes({
"GET /item": function() {
return {status: 200, responseText: JSON.stringify({a: 1})}
}
})
xhr({
method: "GET", url: "/item",
extract: function() {throw new Error("error")}
}).catch(function(e) {
o(e instanceof Error).equals(true)
o(e.message).equals("error")
}).then(function() {
done()
})
})
})
})