React-starter-kit: Declarative routes with GraphQL and Relay

Created on 11 Jul 2016  路  1Comment  路  Source: kriasoft/react-starter-kit

I have created the bare minimum declarative vs imperative routing projects here to play with:

https://github.com/koistya/demos

RSK is currently using imperative (or, functional) routes. But if you're using Relay in your project, declarative routes might also be a good option. Here is an example (routes.json):

[
  {
    "path": "/tasks/:status(pending|completed)?",
    "queries": {
      "viewer": "query { viewer }",
      "tasks": "query { tasks(status: $status) }"
    },
    "component": "./routes/TaskList"
  },
  {
    "path": "/tasks/:id(\\d+)",
    "queries": {
      "viewer": "query { viewer }",
      "tasks": "query { task(id: $id) }"
    },
    "component": "./routes/TaskDetails"
  }
]

By using a simple loader for Webpack (see routes-loader.js) you can transform such routes into JavaScript during compilation by using wonderful path-to-regexp library. So that when you reference the routes.json file in your code (e.g. import routes from './routes.json') it will be transformed into something like this:

[
  {
    path: '/tasks/:status(pending|completed)?',
    pattern: /^\/tasks(?:\/((?:pending|completed)))?(?:\/(?=$))?$/i,
    keys: [{ name: 'status', ... }],
    queries: {
      viewer: () => Relay.QL`query { viewer }`,
      tasks: () => Relay.QL`query { tasks(status: $status) }`
    },
    component: './routes/TaskList',
    load: () => System.import('./routes/TaskList').then(x => x.default);
  },
  {
    path: '/tasks/:id(\\d+)',
    pattern: /^\/tasks\/((?:[^\/]+?))(?:\/(?=$))?$/i,
    keys: [{ name: 'id', ... }],
    queries: {
      viewer: () => Relay.QL`query { viewer }`,
      tasks: () => Relay.QL`query { task(id: $id) }`
    },
    component: './routes/TaskDetails',
    load: () => System.import('./routes/TaskDetails').then(x => x.default);
  }
]

You can find a working example of this approach in the React Static Boilerplate (RSB) project.

P.S.: This issue is created solely for discussion. Upvote or downvote this approach, add comments.

Ref #20

discussion

Most helpful comment

DSL (Domain Specific Languages) are awesome. Why we do not use them? Because they are _specific_. Same here.
Do you really think that loader can be better than raw code? I'm skeptic in this..

Keep in mind how much confusion can import 'assets' do...

>All comments

DSL (Domain Specific Languages) are awesome. Why we do not use them? Because they are _specific_. Same here.
Do you really think that loader can be better than raw code? I'm skeptic in this..

Keep in mind how much confusion can import 'assets' do...

Was this page helpful?
0 / 5 - 0 ratings

Related issues

artkynet picture artkynet  路  4Comments

shawn-dsz picture shawn-dsz  路  4Comments

rochadt picture rochadt  路  3Comments

pfftdammitchris picture pfftdammitchris  路  3Comments

Jeff-Kook picture Jeff-Kook  路  3Comments