Skip to content

Releases: moleculerjs/moleculer-web

v0.6.0

04 Jan 12:25
Compare
Choose a tag to compare

Breaking changes

Alias custom function arguments is changed

The route first argument is removed. The new signature of function is function(req, res) {}. To access to route use the req.$route property.
However you can use an array of Function for aliases. With it you can call middlewares. In this case the third argument is next. I.e.: function(req, res, next) {}.

Other changes

  • better error handling. Always returns with JSON error response.
  • The charset is UTF-8 for application/json responses.
  • logRequestParams setting to log the request parameters. Use log level value i.e. "debug", "info" or null to disable.
  • logResponseData setting to log the response data. Use log level value i.e. "debug", "info" or null to disable.
  • req.$service & res.$service is pointed to the service instance.
  • req.$route & res.$route is pointed to the route definition.
  • req.$params is pointed to the resolved parameters (from query string & post body)
  • req.$alias is pointed to the alias definition.
  • req.$endpoint is pointed to the resolved action endpoint. It contains action and nodeID.

Middlewares

Support middlewares in global, routes & aliases.

broker.createService({
    mixins: [ApiService],
    settings: {
        // Global middlewares. Applied to all routes.
        use: [
            cookieParser(),
            helmet()
        ],

        routes: [
            {
                path: "/",

                // Route-level middlewares.
                use: [
                    compression(),
                    
                    passport.initialize(),
                    passport.session(),

                    serveStatic(path.join(__dirname, "public"))
                ],
                
                aliases: {
                    "GET /secret": [
                        // Alias-level middlewares.
                        auth.isAuthenticated(),
                        auth.hasRole("admin"),
                        "top.secret" // Call the `top.secret` action
                    ]
                }
            }
        ]
    }
});

Custom response headers

It supports custom response headers to define in action definition.

module.exports = {
    name: "export",
    actions: {
        downloadCSV: 
            responseHeaders: {
                "Content-Disposition": "attachment; filename=\"data.csv\"",
                "Content-Type": "text/csv"
            },
            handler() {
                return "...";
            }
        }
    }
}

Error handlers

You can add route & global custom error handlers.

broker.createService({
    mixins: [ApiService],
    settings: {

        routes: [{
            path: "/api",

            // Route error handler
            onError(req, res, err) {
                res.setHeader("Content-Type", "application/json; charset=utf-8");
                res.writeHead(500);
                res.end(JSON.stringify(err));
            }
        }],

        // Global error handler
        onError(req, res, err) {
            res.setHeader("Content-Type", "text/plain");
            res.writeHead(501);
            res.end("Global error: " + err.message);
        }		
    }
}

New examples to serve client-side developing with Webpack

v0.5.2

24 Oct 14:10
Compare
Choose a tag to compare

New

  • add mappingPolicy route option

v0.5.1

07 Oct 19:50
Compare
Choose a tag to compare

New

  • add CORS headers
  • add Rate limiter

v0.5.0

07 Oct 15:33
Compare
Choose a tag to compare

Breaking changes

  • compatibility with Moleculer >= v0.11.x

v0.4.4

20 Aug 08:54
Compare
Choose a tag to compare

Changes

  • update Moleculer to v0.10

v0.4.1

24 Jul 09:46
Compare
Choose a tag to compare

New

Prohibited action with publish: false action properties

module.exports = {
    name: "test",
    actions: {
        dangerZone: {
            publish: false,
            handler(ctx) {
                return "You cannot call this action via API Gateway!";
            }
        }
    }
};

Calling options in routes

The route has a callOptions property which is passed to broker.call. So you can set timeout, retryCount or fallbackResponse options for routes.

broker.createService(ApiGatewayService, {
    settings: {
        routes: [{
            
            callOptions: {
                timeout: 1000, // 1 sec
                retryCount: 0,
                //fallbackResponse: { ... },
                // or 
                //fallbackResponse(ctx, err) { ... }
            }

        }]
    }
});

v0.4.0

24 Jul 09:43
Compare
Choose a tag to compare

Breaking changes

  • in the REST shorthand, the GET / calls the list action instead of find. The reason is list action in moleculer-db is support pagination

Changes

  • changed order of param handling ctx.params = Object.assign({}, body, query, params).
  • moved onBeforeCall before authorize in request flow. So you can also reach unauthorized requests in onBeforeCall handler.
  • the sendResponse method has new arguments: sendResponse(ctx, route, req, res, data, responseType)

v0.3.3

07 Jun 09:40
Compare
Choose a tag to compare

New

Functions in aliases

There is available to use custom function in aliases. In this case you got req & res and you should return with the response. Use it for example file uploads. You can find example in the full example.

Usage

    ...
        aliases: {
            "add/:a/:b": "math.add",
            "GET sub": "math.sub",
            "POST upload"(route, req, res) {
                //Do something and call res.end()
            }
        }
    ...

New camelCaseNames route setting

There is a new camelCaseNames option in route setting. If it is true, the service will convert the received action name to camelCase name.

Usage

broker.createService(ApiGatewayService, {
    settings: {
        routes: [{
            camelCaseNames: true
        }]
    }
});

broker.createService({
    name: "test",
    actions: {
        sayHi(ctx) {
            return "Hi!"
        }
    }
});

// Start server
broker.start();

In the above example the sayHi action can be called with http://localhost:3000/test/say-hi as well.

v0.3.2

02 Jun 19:50
Compare
Choose a tag to compare

New

Exposed error classes

Available errors:

Class Params Description
UnAuthorizedError type, data Unauthorized HTTP error (401)
ForbiddenError type, data Forbidden HTTP error (403)
BadRequestError type, data Bad Request HTTP error (400)

Type contants:

  • ERR_NO_TOKEN
  • ERR_INVALID_TOKEN
  • ERR_UNABLE_DECODE_PARAM

Usage

const { UnAuthorizedError, ERR_NO_TOKEN } = require("moleculer-web").Errors;
    ...
    actions: {
        update(ctx) {
            if(!ctx.meta.user)
                return Promise.reject(new UnAuthorizedError(ERR_NO_TOKEN));
        }
    }
    ...

v0.3.1

02 Jun 18:03
Compare
Choose a tag to compare

New

RESTful routes

It is possible to use RESTful aliases which routed to CRUD service actions.

Usage

broker.createService(ApiGatewayService, {
    settings: {
        routes: [{
            // RESTful aliases
            aliases: {
                "REST posts": "posts"
            }
        }]
    }
});

// Start server
broker.start();

The "REST posts": "posts" will be extracted to these aliases:

"GET posts":        "posts.find",
"GET posts/:id":    "posts.get",
"POST posts":       "posts.create",
"PUT posts/:id":    "posts.update",
"DELETE posts/:id": "posts.remove"				

Example: examples/rest