mithril-vndb/docs/paths.md
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

6.1 KiB

Path Handling


m.route, m.request, and m.jsonp each have a concept called a path. This is used to generate the URL you route to or fetch from.

Path types

There are two general types of paths: raw paths and parameterized paths.

  • Raw paths are simply strings used directly as URLs. Nothing is substituted or even split. It's just normalized with all the parameters appended to the end.
  • Parameterized paths let you insert values into paths, escaped by default for convenience and safety against URL injection.

For m.request and m.jsonp, these can be pretty much any URL, but for routes, these can only be absolute URL path names without schemes or domains.

Path parameters

Path parameters are themselves pretty simple. They come in two forms:

  • :foo - This injects a simple params.foo into the URL, escaping its value first.
  • :foo... - This injects a raw params.foo path into the URL without escaping anything.

You're probably wondering what that params object is supposed to be. It's pretty simple: it's the params in either m.route.set(path, params), m.request({url, params}), or m.jsonp({url, params}).

When receiving routes via m.route(root, defaultRoute, routes), you can use these parameters to extract values from routes. They work basically the same way as generating the paths, just in the opposite direction.

// Edit a single item
m.route(document.body, "/edit/1", {
	"/edit/:id": {
    	view: function() {
    		return [
    			m(Menu),
    			m("h1", "Editing user " + m.route.param("id"))
    		]
    	}
    },
})

// Edit an item identified by path
m.route(document.body, "/edit/pictures/image.jpg", {
	"/edit/:file...": {
    	view: function() {
    		return [
    			m(Menu),
    			m("h1", "Editing file " + m.route.param("file"))
    		]
    	}
    },
})

In the first example, assuming you're navigating to the default route in each, m.route.param("id") would be read as "1" and m.route.param("file") would be read as pictures/image.jpg.

Path parameters may be delimited by either a /, -, or .. This lets you have dynamic path segments, and they're considerably more flexible than just a path name. For example, you could match against routes like "/edit/:name.:ext" for editing based on file extension or "/:lang-:region/view" for a localized route.

Path parameters are greedy: given a declared route "/edit/:name.:ext", if you navigate to /edit/file.test.png, the parameters extracted will be {name: "file.test", ext: "png"}, not {name: "file", ext: "test.png"}. Similarly, given "/route/:path.../view/:child...", if you go to /route/foo/view/bar/view/baz, the parameters extracted will be {path: "foo/view/bar", child: "baz"}.

Parameter normalization

Path parameters that are interpolated into path names are omitted from the query string, for convenience and to keep the path name reasonably readable. For example, this sends a server request of GET /api/user/1/connections?sort=name-asc, omitting the duplicate id=1 in the URL string.

m.request({
    url: "https://example.com/api/user/:userID/connections",
    params: {
        userID: 1,
        sort: "name-asc"
    }
})

You can also specify parameters explicitly in the query string itself, such as in this, which is equivalent to the above:

m.request({
    url: "https://example.com/api/user/:userID/connections?sort=name-asc",
    params: {
        userID: 1
    }
})

And of course, you can mix and match. This fires a request to GET /api/user/1/connections?sort=name-asc&first=10.

m.request({
    url: "https://example.com/api/user/:userID/connections?sort=name-asc",
    params: {
        userID: 1,
        first: 10
    }
})

This even extends to route matching: you can match against a route with explicit query strings. It retains the matched parameter for convenience, so you can still access them via vnode parameters or via m.route.param. Note that although this is possible, it's not generally recommended, since you should prefer paths for pages. It could sometimes useful if you need to generate a somewhat different view just for a particular file type, but it still logically is a query-like parameter, not a whole separate page.

// Note: this is generally *not* recommended - you should prefer paths for route
// declarations, not query strings.
m.route(document.body, "/edit/1", {
	"/edit?type=image": {
    	view: function() {
    		return [
    			m(Menu),
    			m("h1", "Editing photo")
    		]
    	}
    },
    "/edit": {
        view: function() {
    		return [
    			m(Menu),
    			m("h1", "Editing " + m.route.param("type"))
    		]
    	}
    }
})

Note that query parameters are implicit - you don't need to name them to accept them. You can match based on an existing value, like in "/edit?type=image", but you don't need to use "/edit?type=:type" to accept the value. In fact, Mithril would treat that as you trying to literally match against m.route.param("type") === ":type". Or in summary, use m.route.param("key") to extract parameters - it simplifies things.

Path normalization

Parsed paths are always returned with all the duplicate parameters and extra slashes dropped, and they always start with a slash. These little differences often get in the way, and it makes routing and path handling a lot more complicated than it should be. Mithril internally normalizes paths for routing, but it does not expose the current, normalized route directly. (You could compute it via m.parsePathname(m.route.get()).path.)

When parameters are deduplicated during matching, parameters in the query string are preferred over parameters in the path name, and parameters towards the end of the URL are preferred over parameters closer to the start of the URL.