1.2.0
Server router with authentication for Meteor
Introductory blog post: https://blog.hagmajer.com/server-side-routing-with-authentication-in-meteor-6625ed832a94.
Documentation: https://mhagmajer.github.io/server-router/.
Please beware that:
meteor add mhagmajer:server-router
You can find Flow type definitions in /definitions
.
import { ServerRouter } from 'meteor/mhagmajer:server-router';
WebApp.connectHandlers.use(ServerRouter.middleware({
paths: [],
routes: {
hello(name) {
this.res.end(`You ${name}, your id is ${this.userId}`);
},
},
}));
import { ServerRouterClient } from 'meteor/mhagmajer:server-router';
const serverRouterClient = new ServerRouterClient({
routes: {
hello: 1,
},
});
<Button onClick={() => {
serverRouterClient.redirect.hello('John');
}} />
Run npm run clean
before meteor publish
.
Basic object of the router representing a server-side path available via HTTP request.
For each path
matching the request url, a handler (Route) is called with this
bound
to the context of the request (ServerRouterContext).
Initalized with the following data:
options: Optional data passed to path-to-regexp
.
params
and query
to route arguments.path
matches.Type: {path: string, options: {sensitive: boolean?, strict: boolean?, end: boolean?, delimiter: string?}?, args: ArgsMapper, route: Route}
(string)
(boolean?)
(boolean?)
(boolean?)
(string?)
(ArgsMapper)
(Route)
serverRouter.addPath({
path: '/binary-representation/:n',
args: ({ n }) => [Number(n)],
async route(n) {
this.res.end(n.toString(2));
},
});
// GET /binary-representation/1337
// 10100111001
serverRouter.addPath({
path: '/sum/:n+',
args: ({ n }) => n.map(Number),
async route(...nums) {
this.res.end(String(nums.reduce((a, b) => a + b)));
},
});
// GET /sum/1/2/3
// 6
serverRouter.addPath({
path: '/get-query',
args: (params, query) => [query],
async route(query) {
this.res.end(String(Object.keys(query)));
},
});
// GET /get-query?a=&b=
// a,b
Function used to map params and query to actual route arguments.
Type: function (params: {}, query: {}): Array<any>
Array<any>
:
arguments that the route will be called with.
Path handler called with this
bound to ServerRouterContext.
In order to respond to HTTP request, you should write to this.res
object. By default, request
processing is finished once your handler finishes. If you want to disable this behavior, you can
return false
to pass the processing to the next handler. Note that the response (this.res
)
must eventually be ended during the HTTP request processing by a route within ServerRouter or
some other middleware.
Any exceptions thrown in handlers other than AuthenticationRequiredError are presented in response.
Type: function (): Promise<(void | boolean)>
Promise<(boolean | void)>
:
whether the request processing is complete (defaults to true).
this.userId
to be set to the current user (if any).
Object to which this
is bound to inside your Route invocation. It provides the
following:
This object is preserved between calling matched routes, so you can augment it.
Type: {req: IncomingMessage, res: ServerResponse, userId: string?}
Nested dictionary of Route functions. This allows for namespaces.
Type: {}
serverRouter.addRoutes({
reports: {
salesPDF, // available by name 'reports.salesPDF'
employeesPDF,
},
images: {
pngs: {
async logo() { ... }, // name: 'images.pngs.logo'
},
},
});
Server-side routing provider of the connect API that can be used with Meteor webapp package.
Name | Description |
---|---|
options.paths Array<Path>?
(default [] )
|
Initial paths. You can add more with #ServerRouter#addPaths or #ServerRouter#addPath . |
options.routes Routes?
(default {} )
|
Initial routes. You can add more with #ServerRouter#addRoutes . |
options.defaultRoutePath string?
(default /r/:name/:args* )
|
Any added Route can be reached by this path when provided its nested name and arguments. See Path for more on syntax. Should be unique for every ServerRouter instance (if you need more than one). Arguments are serialized with EJSON for transportation. |
WebApp.connectHandlers.use((new ServerRouter({
routes: { ... },
paths: [ ... ],
})).middleware);
WebApp.connectHandlers.use(ServerRouter.middleware({
routes: { ... },
paths: [ ... ],
}));
const serverRouter = new ServerRouter();
WebApp.connectHandlers.use(serverRouter.middleware);
serverRouter.addPaths([ ... ]);
serverRouter.addRoutes({ ... });
Short for (new ServerRouter(options)).middleware
.
(any)
Adds a list of paths. Short for calling #ServerRouter#addPath a number of times.
Thrown by routes when authentication is required for further processing.
Client for ServerRouter
({routes: R?, defaultRoutePath: string?})
Name | Description |
---|---|
options.routes Routes
(default {} )
|
Known server-side routes. When providing this object you can
substitute function with anything other than object. For example:
const x: any = 1;
const routes: Routes = {
Reports: {
genReport: x,
genReport2: x,
},
};
This is used to populate #ServerRouterClient#url and |
options.defaultRoutePath string
(default /r/:name/:args* )
|
Same as in ServerRouter . |
Convenient methods for redirecting to a server route with authentication.
Type: R
serverRouterClient.redirect.privateImages.img1(800, 600);
Convenient getters of paths for server routes. Compatible with static type checkers like Flow.
Note: These methods return string, not Promise.
Type: R
console.log(serverRouterClient.path.privateImages.img1(800, 600));
Redirects to given route and args with authenication. Short for (example):
serverRouterClient.redirectTo(serverRouterClient.getRoutePath('privateImages.img1', 800, 600));
Returns a promise for the same reason like #ServerRouterClient#redirectTo.