diff --git a/.editorconfig b/.editorconfig index 1fa27f9a..d1ca5085 100644 --- a/.editorconfig +++ b/.editorconfig @@ -19,10 +19,16 @@ insert_final_newline = true [*.md] trim_trailing_whitespace = false +indent_style = space +indent_size = 4 [{package,bower}.json] indent_style = space indent_size = 2 +[*.yml] +indent_style = space +indent_size = 2 + [*.js] quote_type = "double" diff --git a/.eslintrc.js b/.eslintrc.js deleted file mode 100644 index 049f9f0b..00000000 --- a/.eslintrc.js +++ /dev/null @@ -1,68 +0,0 @@ -module.exports = { - "env": { - "node": true, - "commonjs": true, - "es6": true, - "jquery": false, - "jest": true, - "jasmine": true - }, - "extends": [ - "eslint:recommended", - "plugin:security/recommended" - ], - "parserOptions": { - "sourceType": "module", - "ecmaVersion": "2018" - }, - "plugins": [ - "promise", - "security" - ], - "rules": { - "indent": [ - "warn", - "tab", - { SwitchCase: 1 } - ], - "quotes": [ - "warn", - "double" - ], - "semi": [ - "error", - "always" - ], - "no-var": [ - "error" - ], - "no-console": [ - "error" - ], - "no-unused-vars": [ - "warn" - ], - "no-trailing-spaces": [ - "error" - ], - "no-alert": 0, - "no-shadow": 0, - "security/detect-object-injection": ["off"], - "security/detect-non-literal-require": ["off"], - "security/detect-non-literal-fs-filename": ["off"], - "no-process-exit": ["off"], - "node/no-unpublished-require": 0, - "space-before-function-paren": [ - "warn", - { - "anonymous": "never", - "named": "never", - "asyncArrow": "always" - } - ], - "object-curly-spacing": [ - "warn", - "always" - ] - } -}; diff --git a/benchmarks/cluster/index.js b/benchmarks/cluster/index.js index 19c7104d..71f1abef 100644 --- a/benchmarks/cluster/index.js +++ b/benchmarks/cluster/index.js @@ -1,25 +1,31 @@ -/* eslint-disable no-console */ - "use strict"; -const - os = require("os"), +const os = require("os"), cluster = require("cluster"), stopSignals = [ - "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP", "SIGABRT", - "SIGBUS", "SIGFPE", "SIGUSR1", "SIGSEGV", "SIGUSR2", "SIGTERM" + "SIGHUP", + "SIGINT", + "SIGQUIT", + "SIGILL", + "SIGTRAP", + "SIGABRT", + "SIGBUS", + "SIGFPE", + "SIGUSR1", + "SIGSEGV", + "SIGUSR2", + "SIGTERM" ], production = true; //process.env.NODE_ENV == "production"; let stopping = false; -cluster.on("disconnect", function(worker) { +cluster.on("disconnect", function (worker) { if (production) { if (!stopping) { cluster.fork(); } - } else - process.exit(1); + } else process.exit(1); }); if (cluster.isMaster) { @@ -30,11 +36,11 @@ if (cluster.isMaster) { } if (production) { - stopSignals.forEach(function(signal) { - process.on(signal, function() { + stopSignals.forEach(function (signal) { + process.on(signal, function () { console.log(`Got ${signal}, stopping workers...`); stopping = true; - cluster.disconnect(function() { + cluster.disconnect(function () { console.log("All workers stopped, exiting."); process.exit(0); }); @@ -48,7 +54,6 @@ if (cluster.isMaster) { worker.process.argv.push(hostname + "-worker-" + worker.id); require("./worker.js"); - } /** diff --git a/benchmarks/cluster/worker.js b/benchmarks/cluster/worker.js index d1076e12..9a7a111f 100644 --- a/benchmarks/cluster/worker.js +++ b/benchmarks/cluster/worker.js @@ -1,8 +1,7 @@ -/* eslint-disable no-console */ "use strict"; -const { ServiceBroker } = require("moleculer"); -const ApiService = require("../../index"); +const { ServiceBroker } = require("moleculer"); +const ApiService = require("../../index"); // Create broker const broker = new ServiceBroker({ @@ -24,5 +23,4 @@ broker.createService({ broker.createService(ApiService); // Start server -broker.start() - .then(() => console.log(`Worker '${broker.nodeID}' started.`)); +broker.start().then(() => console.log(`Worker '${broker.nodeID}' started.`)); diff --git a/benchmarks/remote/api/index.js b/benchmarks/remote/api/index.js index 64ad537b..450ee3df 100644 --- a/benchmarks/remote/api/index.js +++ b/benchmarks/remote/api/index.js @@ -1,25 +1,31 @@ -/* eslint-disable no-console */ - "use strict"; -const - os = require("os"), +const os = require("os"), cluster = require("cluster"), stopSignals = [ - "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP", "SIGABRT", - "SIGBUS", "SIGFPE", "SIGUSR1", "SIGSEGV", "SIGUSR2", "SIGTERM" + "SIGHUP", + "SIGINT", + "SIGQUIT", + "SIGILL", + "SIGTRAP", + "SIGABRT", + "SIGBUS", + "SIGFPE", + "SIGUSR1", + "SIGSEGV", + "SIGUSR2", + "SIGTERM" ], production = true; //process.env.NODE_ENV == "production"; let stopping = false; -cluster.on("disconnect", function(worker) { +cluster.on("disconnect", function (worker) { if (production) { if (!stopping) { cluster.fork(); } - } else - process.exit(1); + } else process.exit(1); }); if (cluster.isMaster) { @@ -30,11 +36,11 @@ if (cluster.isMaster) { } if (production) { - stopSignals.forEach(function(signal) { - process.on(signal, function() { + stopSignals.forEach(function (signal) { + process.on(signal, function () { console.log(`Got ${signal}, stopping workers...`); stopping = true; - cluster.disconnect(function() { + cluster.disconnect(function () { console.log("All workers stopped, exiting."); process.exit(0); }); @@ -48,7 +54,6 @@ if (cluster.isMaster) { worker.process.argv.push(hostname + "-api-" + worker.id); require("./worker.js"); - } /** diff --git a/benchmarks/remote/api/worker.js b/benchmarks/remote/api/worker.js index d1557360..d961e2ab 100644 --- a/benchmarks/remote/api/worker.js +++ b/benchmarks/remote/api/worker.js @@ -1,8 +1,7 @@ -/* eslint-disable no-console */ "use strict"; -let { ServiceBroker } = require("moleculer"); -let ApiService = require("../../../index"); +let { ServiceBroker } = require("moleculer"); +let ApiService = require("../../../index"); // Create broker let broker = new ServiceBroker({ @@ -17,5 +16,4 @@ let broker = new ServiceBroker({ broker.createService(ApiService); // Start server -broker.start() - .then(() => console.log(`Worker '${broker.nodeID}' started.`)); +broker.start().then(() => console.log(`Worker '${broker.nodeID}' started.`)); diff --git a/benchmarks/remote/worker/index.js b/benchmarks/remote/worker/index.js index f3d858d2..51dc37d7 100644 --- a/benchmarks/remote/worker/index.js +++ b/benchmarks/remote/worker/index.js @@ -1,25 +1,31 @@ -/* eslint-disable no-console */ - "use strict"; -const - os = require("os"), +const os = require("os"), cluster = require("cluster"), stopSignals = [ - "SIGHUP", "SIGINT", "SIGQUIT", "SIGILL", "SIGTRAP", "SIGABRT", - "SIGBUS", "SIGFPE", "SIGUSR1", "SIGSEGV", "SIGUSR2", "SIGTERM" + "SIGHUP", + "SIGINT", + "SIGQUIT", + "SIGILL", + "SIGTRAP", + "SIGABRT", + "SIGBUS", + "SIGFPE", + "SIGUSR1", + "SIGSEGV", + "SIGUSR2", + "SIGTERM" ], production = true; //process.env.NODE_ENV == "production"; let stopping = false; -cluster.on("disconnect", function(worker) { +cluster.on("disconnect", function (worker) { if (production) { if (!stopping) { cluster.fork(); } - } else - process.exit(1); + } else process.exit(1); }); if (cluster.isMaster) { @@ -48,5 +54,4 @@ if (cluster.isMaster) { worker.process.argv.push(hostname + "-worker-" + worker.id); require("./worker.js"); - } diff --git a/benchmarks/remote/worker/worker.js b/benchmarks/remote/worker/worker.js index 8766b01f..f80a12d0 100644 --- a/benchmarks/remote/worker/worker.js +++ b/benchmarks/remote/worker/worker.js @@ -1,6 +1,6 @@ "use strict"; -let { ServiceBroker } = require("moleculer"); +let { ServiceBroker } = require("moleculer"); // Create broker let broker = new ServiceBroker({ @@ -21,5 +21,4 @@ broker.createService({ }); // Start server -broker.start() - .then(() => console.log(`Worker '${broker.nodeID}' started.`)); +broker.start().then(() => console.log(`Worker '${broker.nodeID}' started.`)); diff --git a/benchmarks/simple/index.js b/benchmarks/simple/index.js index bafb5bb9..c916f317 100644 --- a/benchmarks/simple/index.js +++ b/benchmarks/simple/index.js @@ -1,8 +1,7 @@ -/* eslint-disable no-console */ "use strict"; -const { ServiceBroker } = require("moleculer"); -const ApiService = require("../../index"); +const { ServiceBroker } = require("moleculer"); +const ApiService = require("../../index"); // Create broker const broker = new ServiceBroker({ @@ -23,8 +22,7 @@ broker.createService({ broker.createService(ApiService); // Start server -broker.start() - .then(() => console.log("Test URL: http://localhost:3000/test/hello")); +broker.start().then(() => console.log("Test URL: http://localhost:3000/test/hello")); /** * Result on i7 4770K 32GB RAM Windows 10 x64 diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 00000000..4586288c --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,56 @@ +const js = require("@eslint/js"); +const globals = require("globals"); +const eslintPluginPrettierRecommended = require("eslint-plugin-prettier/recommended"); + +/** @type {import('eslint').Linter.FlatConfig[]} */ +module.exports = [ + js.configs.recommended, + eslintPluginPrettierRecommended, + { + files: ["**/*.js", "**/*.mjs"], + languageOptions: { + parserOptions: { + sourceType: "module", + ecmaVersion: 2023 + }, + globals: { + ...globals.node, + ...globals.es2020, + ...globals.commonjs, + ...globals.es6, + ...globals.jquery, + ...globals.jest, + ...globals.jasmine, + process: "readonly", + fetch: "readonly" + } + }, + // plugins: ["node", "security"], + rules: { + "no-var": ["error"], + "no-console": ["error"], + "no-unused-vars": ["warn"], + "no-trailing-spaces": ["error"], + "security/detect-object-injection": ["off"], + "security/detect-non-literal-require": ["off"], + "security/detect-non-literal-fs-filename": ["off"], + "no-process-exit": ["off"], + "node/no-unpublished-require": 0 + }, + ignores: ["benchmark/test.js", "test/typescript/hello-world/out/*.js"] + }, + { + files: ["test/**/*.js"], + rules: { + "no-console": ["off"], + "no-unused-vars": ["off"] + } + }, + { + files: ["benchmarks/**/*.js", "examples/**/*.js"], + rules: { + "no-console": ["off"], + "no-unused-vars": ["off"] + } + } +]; diff --git a/examples/auth.service.js b/examples/auth.service.js index 939e7019..a3d15fa8 100644 --- a/examples/auth.service.js +++ b/examples/auth.service.js @@ -6,10 +6,10 @@ "use strict"; -const jwt = require("jsonwebtoken"); -const _ = require("lodash"); -const { MoleculerError } = require("moleculer").Errors; -const { promisify } = require("util"); +const jwt = require("jsonwebtoken"); +const _ = require("lodash"); +const { MoleculerError } = require("moleculer").Errors; +const { promisify } = require("util"); const JWT_SECRET = "TOP SECRET!!!"; @@ -39,14 +39,15 @@ module.exports = { login: { rest: "/login", handler(ctx) { - let user = users.find(u => u.username == ctx.params.username && u.password == ctx.params.password); + let user = users.find( + u => u.username == ctx.params.username && u.password == ctx.params.password + ); if (user) { return this.generateToken(user).then(token => { return { token }; }); - } else - return Promise.reject(new MoleculerError("Invalid credentials", 400)); + } else return Promise.reject(new MoleculerError("Invalid credentials", 400)); } }, @@ -92,7 +93,7 @@ module.exports = { } }); } - }, + } }, created() { diff --git a/examples/authentication/index.js b/examples/authentication/index.js index 21daab6a..ba49aea7 100644 --- a/examples/authentication/index.js +++ b/examples/authentication/index.js @@ -13,9 +13,9 @@ * */ -let path = require("path"); -let { ServiceBroker } = require("moleculer"); -let ApiGatewayService = require("../../index"); +let path = require("path"); +let { ServiceBroker } = require("moleculer"); +let ApiGatewayService = require("../../index"); // Create broker let broker = new ServiceBroker({ @@ -30,7 +30,6 @@ broker.createService({ mixins: [ApiGatewayService], settings: { - routes: [ { // Enable authentication diff --git a/examples/authorization/index.js b/examples/authorization/index.js index e8ec80dd..2d11a39f 100644 --- a/examples/authorization/index.js +++ b/examples/authorization/index.js @@ -13,9 +13,9 @@ * */ -let path = require("path"); -let { ServiceBroker } = require("moleculer"); -let ApiGatewayService = require("../../index"); +let path = require("path"); +let { ServiceBroker } = require("moleculer"); +let ApiGatewayService = require("../../index"); const { UnAuthorizedError, ERR_NO_TOKEN, ERR_INVALID_TOKEN } = require("../../src/errors"); @@ -32,7 +32,6 @@ broker.createService({ mixins: [ApiGatewayService], settings: { - routes: [ { // Enable authorization @@ -59,12 +58,8 @@ broker.createService({ // Set the authorized user entity to `ctx.meta` ctx.meta.user = { id: 1, name: "John Doe" }; return Promise.resolve(ctx); - - } else - return Promise.reject(new UnAuthorizedError(ERR_INVALID_TOKEN)); - - } else - return Promise.reject(new UnAuthorizedError(ERR_NO_TOKEN)); + } else return Promise.reject(new UnAuthorizedError(ERR_INVALID_TOKEN)); + } else return Promise.reject(new UnAuthorizedError(ERR_NO_TOKEN)); } } }); diff --git a/examples/auto-aliases/index.js b/examples/auto-aliases/index.js index 7bc4ec9e..2c34ee56 100644 --- a/examples/auto-aliases/index.js +++ b/examples/auto-aliases/index.js @@ -13,9 +13,9 @@ * */ -let path = require("path"); -let { ServiceBroker } = require("moleculer"); -let ApiService = require("../../index"); +let path = require("path"); +let { ServiceBroker } = require("moleculer"); +let ApiService = require("../../index"); // Create broker let broker = new ServiceBroker({ @@ -36,17 +36,13 @@ broker.createService({ { path: "api", - whitelist: [ - "api.*", - "**posts.*", - "test.*" - ], + whitelist: ["api.*", "**posts.*", "test.*"], use: [ - function(req, res, next) { + function (req, res, next) { this.logger.info("Middleware ", this.name); next(); - }, + } ], aliases: { @@ -58,10 +54,7 @@ broker.createService({ { path: "/admin", - whitelist: [ - "auth.*", - "$node.*" - ], + whitelist: ["auth.*", "$node.*"], aliases: { "GET /services": "$node.services" diff --git a/examples/cors/index.js b/examples/cors/index.js index 35a13c3b..6cd7a2c7 100644 --- a/examples/cors/index.js +++ b/examples/cors/index.js @@ -5,7 +5,7 @@ */ const { ServiceBroker } = require("moleculer"); -const ApiService = require("../../index"); +const ApiService = require("../../index"); // Create broker const broker = new ServiceBroker(); @@ -32,23 +32,23 @@ broker.createService({ path: "/api1", aliases: { - "welcome": { + welcome: { method: "POST", fullPath: "/welcome", action: "greeter.welcome" } - }, + } }, { path: "/api2", aliases: { - "welcome": { + welcome: { method: "POST", fullPath: "/api2/welcome", action: "greeter.welcome" } - }, + } } ] } diff --git a/examples/dev/index.js b/examples/dev/index.js index c00b4f31..afa7f706 100644 --- a/examples/dev/index.js +++ b/examples/dev/index.js @@ -1,7 +1,7 @@ "use strict"; -const { ServiceBroker } = require("moleculer"); -const ApiService = require("../../index"); +const { ServiceBroker } = require("moleculer"); +const ApiService = require("../../index"); // Create broker const broker = new ServiceBroker(); @@ -17,14 +17,14 @@ broker.createService({ name: "no-auth-route", path: "/", aliases: { - hi: "greeter.hello", + hi: "greeter.hello" } }, { name: "only-auth-route", path: "/", aliases: { - "hello": "greeter.hello", + hello: "greeter.hello" }, authorization: true } diff --git a/examples/direct-calls/index.js b/examples/direct-calls/index.js index f3a0c2e8..33c18077 100644 --- a/examples/direct-calls/index.js +++ b/examples/direct-calls/index.js @@ -13,14 +13,14 @@ * GET http://localhost:3000/node-2/where */ -let path = require("path"); -let { ServiceBroker } = require("moleculer"); -let ApiService = require("../../index"); +let path = require("path"); +let { ServiceBroker } = require("moleculer"); +let ApiService = require("../../index"); // Create broker let broker = new ServiceBroker({ nodeID: "api", - transporter: "NATS", + transporter: "NATS" }); // Load API Gateway @@ -48,20 +48,20 @@ broker.createService({ callOptions: { nodeID: "node-2" } - }, + } ] } }); const node1 = new ServiceBroker({ nodeID: "node-1", - transporter: "NATS", + transporter: "NATS" }); node1.loadService(path.join(__dirname, "..", "test.service.js")); const node2 = new ServiceBroker({ nodeID: "node-2", - transporter: "NATS", + transporter: "NATS" }); node2.loadService(path.join(__dirname, "..", "test.service.js")); diff --git a/examples/express/index.js b/examples/express/index.js index d0dd24a3..895dd16e 100644 --- a/examples/express/index.js +++ b/examples/express/index.js @@ -12,10 +12,10 @@ * http://localhost:3333/api/hi?name=John */ -let path = require("path"); -let { ServiceBroker } = require("moleculer"); -let ApiGatewayService = require("../../index"); -let express = require("express"); +let path = require("path"); +let { ServiceBroker } = require("moleculer"); +let ApiGatewayService = require("../../index"); +let express = require("express"); // Create broker let broker = new ServiceBroker({ @@ -31,16 +31,15 @@ const svc = broker.createService({ settings: { server: false, - routes: [{ - whitelist: [ - "test.hello", - "test.greeter" - ], - aliases: { - "GET hi": "test.greeter" - }, - mappingPolicy: "all" - }] + routes: [ + { + whitelist: ["test.hello", "test.greeter"], + aliases: { + "GET hi": "test.greeter" + }, + mappingPolicy: "all" + } + ] } }); @@ -52,8 +51,7 @@ app.use("/api", svc.express()); // Listening app.listen(3333, err => { - if (err) - return console.error(err); + if (err) return console.error(err); console.log("Open http://localhost:3333/api/test/hello"); }); diff --git a/examples/express/index2.js b/examples/express/index2.js index 9e88f467..54bb86e2 100644 --- a/examples/express/index2.js +++ b/examples/express/index2.js @@ -12,10 +12,10 @@ * http://localhost:3333/api/hi?name=John */ -const path = require("path"); +const path = require("path"); const { ServiceBroker } = require("moleculer"); const ApiGatewayService = require("../../index"); -const express = require("express"); +const express = require("express"); // Create broker const broker = new ServiceBroker(); @@ -29,20 +29,18 @@ broker.createService({ settings: { server: false, - routes: [{ - whitelist: [ - "test.hello", - "test.greeter" - ], - aliases: { - "GET hi": "test.greeter" - }, - mappingPolicy: "all" - }] + routes: [ + { + whitelist: ["test.hello", "test.greeter"], + aliases: { + "GET hi": "test.greeter" + }, + mappingPolicy: "all" + } + ] }, started() { - // Create Express application const app = express(); @@ -51,8 +49,7 @@ broker.createService({ // Listening app.listen(3333, err => { - if (err) - return this.logger.error(err); + if (err) return this.logger.error(err); this.logger.info("Open http://localhost:3333/api/hi?name=John"); }); diff --git a/examples/file.service.js b/examples/file.service.js index df5090ee..57bc8e42 100644 --- a/examples/file.service.js +++ b/examples/file.service.js @@ -14,7 +14,9 @@ module.exports = { handler(ctx) { ctx.meta.$responseType = "image/png"; // Return as stream - return fs.createReadStream(path.join(__dirname, "full", "assets", "images", "logo.png")); + return fs.createReadStream( + path.join(__dirname, "full", "assets", "images", "logo.png") + ); } }, @@ -35,8 +37,7 @@ module.exports = { get: { handler(ctx) { const filePath = path.join(uploadDir, ctx.params.file); - if (!fs.existsSync(filePath)) - return new NotFoundError(); + if (!fs.existsSync(filePath)) return new NotFoundError(); ctx.meta.$responseType = mime.lookup(ctx.params.file); // Return as stream @@ -49,7 +50,10 @@ module.exports = { this.logger.info("Received upload params:", ctx.params); return new this.Promise((resolve, reject) => { //reject(new Error("Disk out of space")); - const filePath = path.join(uploadDir, ctx.params.$filename || this.randomName()); + const filePath = path.join( + uploadDir, + ctx.params.$filename || this.randomName() + ); const f = fs.createWriteStream(filePath); f.on("close", () => { // File written successfully diff --git a/examples/file/index.js b/examples/file/index.js index c5f6ce34..ec92aef9 100644 --- a/examples/file/index.js +++ b/examples/file/index.js @@ -113,12 +113,11 @@ broker.createService({ }, mappingPolicy: "restrict" - }, - + } ], assets: { - folder: "./examples/file/assets", + folder: "./examples/file/assets" } } }); diff --git a/examples/formidable/index.js b/examples/formidable/index.js index bb8c4c12..d44778c2 100644 --- a/examples/formidable/index.js +++ b/examples/formidable/index.js @@ -60,7 +60,7 @@ broker.createService({ // File upload from HTML form "POST /multi"(req, res) { return this.handleFileUpload(req, res); - }, + } }, callOptions: { @@ -70,12 +70,11 @@ broker.createService({ }, mappingPolicy: "restrict" - }, - + } ], assets: { - folder: "./examples/formidable/assets", + folder: "./examples/formidable/assets" } }, @@ -92,17 +91,26 @@ broker.createService({ const ctx = req.$ctx; const entries = Array.isArray(files.myfile) ? files.myfile : [files.myfile]; - const result = await Promise.all(entries.map(entry => { - return ctx.call("file.save", { - $filename: entry.name, - ...req.params, - ...fields, - }, { stream: fs.createReadStream(entry.path) }); - })); - - return this.sendResponse(req, res, Array.isArray(files.myfile) ? result : result[0]); + const result = await Promise.all( + entries.map(entry => { + return ctx.call( + "file.save", + { + $filename: entry.name, + ...req.params, + ...fields + }, + { stream: fs.createReadStream(entry.path) } + ); + }) + ); + + return this.sendResponse( + req, + res, + Array.isArray(files.myfile) ? result : result[0] + ); }); - } } }); diff --git a/examples/full/index.js b/examples/full/index.js index 23c141ad..2bbb3f8e 100644 --- a/examples/full/index.js +++ b/examples/full/index.js @@ -46,11 +46,16 @@ * */ -const fs = require("fs"); -const path = require("path"); -const { ServiceBroker } = require("moleculer"); -const { MoleculerError } = require("moleculer").Errors; -const { ForbiddenError, UnAuthorizedError, ERR_NO_TOKEN, ERR_INVALID_TOKEN } = require("../../src/errors"); +const fs = require("fs"); +const path = require("path"); +const { ServiceBroker } = require("moleculer"); +const { MoleculerError } = require("moleculer").Errors; +const { + ForbiddenError, + UnAuthorizedError, + ERR_NO_TOKEN, + ERR_INVALID_TOKEN +} = require("../../src/errors"); // ---- @@ -110,7 +115,6 @@ broker.createService({ path: "/api", routes: [ - /** * This route demonstrates a protected `/api/admin` path to access `users.*` & internal actions. * To access them, you need to login first & use the received token in header @@ -120,15 +124,12 @@ broker.createService({ path: "/admin", // Whitelist of actions (array of string mask or regex) - whitelist: [ - "users.*", - "$node.*" - ], + whitelist: ["users.*", "$node.*"], // Route CORS settings cors: { origin: ["https://localhost:3000", "https://localhost:4000"], - methods: ["GET", "OPTIONS", "POST"], + methods: ["GET", "OPTIONS", "POST"] }, authorization: true, @@ -138,8 +139,8 @@ broker.createService({ // Action aliases aliases: { "POST users": "users.create", - "health": "$node.health", - "custom"(req, res) { + health: "$node.health", + custom(req, res) { res.writeHead(201); res.end(); } @@ -167,7 +168,6 @@ broker.createService({ res.writeHead(err.code || 500); res.end("Route error: " + err.message); } - }, { @@ -210,7 +210,7 @@ broker.createService({ onAfterCall(ctx, route, req, res, data) { this.logger.info("async onAfterCall in upload route"); return new this.Promise(resolve => { - res.setHeader("X-Response-Type", typeof(data)); + res.setHeader("X-Response-Type", typeof data); resolve(data); }); }, @@ -226,18 +226,12 @@ broker.createService({ path: "/", // Middlewares - use: [ - ], + use: [], etag: true, // Whitelist of actions (array of string mask or regex) - whitelist: [ - "auth.*", - "file.*", - "test.*", - /^math\.\w+$/ - ], + whitelist: ["auth.*", "file.*", "test.*", /^math\.\w+$/], authorization: false, @@ -246,8 +240,8 @@ broker.createService({ // Action aliases aliases: { - "login": "auth.login", - "add": "math.add", + login: "auth.login", + add: "math.add", "add/:a/:b": "math.add", "GET sub": "math.sub", "POST divide": "math.div", @@ -261,7 +255,7 @@ broker.createService({ }, callOptions: { - timeout: 3000, + timeout: 3000 //fallbackResponse: "Fallback response via callOptions" }, @@ -277,10 +271,10 @@ broker.createService({ onAfterCall(ctx, route, req, res, data) { this.logger.info("async onAfterCall in public"); return new this.Promise(resolve => { - res.setHeader("X-Response-Type", typeof(data)); + res.setHeader("X-Response-Type", typeof data); resolve(data); }); - }, + } } ], @@ -300,8 +294,7 @@ broker.createService({ },*/ // Do not log client side errors (does not log an error respons when the error.code is 400<=X<500) - log4XXResponses: false, - + log4XXResponses: false }, events: { @@ -362,13 +355,11 @@ broker.createService({ return Promise.reject(new UnAuthorizedError(ERR_NO_TOKEN)); } // Verify JWT token - return ctx.call("auth.resolveToken", { token }) - .then(user => { - if (!user) - return Promise.reject(new UnAuthorizedError(ERR_INVALID_TOKEN)); + return ctx.call("auth.resolveToken", { token }).then(user => { + if (!user) return Promise.reject(new UnAuthorizedError(ERR_INVALID_TOKEN)); - ctx.meta.user = user; - }); + ctx.meta.user = user; + }); } } }); diff --git a/examples/index.js b/examples/index.js index 09910195..63adbca8 100644 --- a/examples/index.js +++ b/examples/index.js @@ -3,4 +3,4 @@ const moduleName = process.argv[2] || "simple"; process.argv.splice(2, 1); -require("./" + moduleName); \ No newline at end of file +require("./" + moduleName); diff --git a/examples/math.service.js b/examples/math.service.js index 9959d098..2620b29c 100644 --- a/examples/math.service.js +++ b/examples/math.service.js @@ -29,10 +29,8 @@ module.exports = { handler(ctx) { let a = Number(ctx.params.a); let b = Number(ctx.params.b); - if (b != 0 && !Number.isNaN(b)) - return a / b; - else - throw new MoleculerClientError("Divide by zero!", 422, null, ctx.params); + if (b != 0 && !Number.isNaN(b)) return a / b; + else throw new MoleculerClientError("Divide by zero!", 422, null, ctx.params); } } } diff --git a/examples/metrics.service.js b/examples/metrics.service.js index ae7eaaef..3c29ce8e 100644 --- a/examples/metrics.service.js +++ b/examples/metrics.service.js @@ -1,19 +1,17 @@ let _ = require("lodash"); -module.exports = function() { +module.exports = function () { return { name: "metrics", events: { - "metrics.trace.span.start"(payload) { this.requests[payload.id] = payload; payload.spans = []; if (payload.parent) { let parent = this.requests[payload.parent]; - if (parent) - parent.spans.push(payload.id); + if (parent) parent.spans.push(payload.id); } }, @@ -21,8 +19,7 @@ module.exports = function() { let item = this.requests[payload.id]; _.assign(item, payload); - if (!payload.parent) - this.printRequest(payload.id); + if (!payload.parent) this.printRequest(payload.id); } }, @@ -37,12 +34,19 @@ module.exports = function() { let gw = 35; let maxTitle = w - 2 - 2 - gw - 2 - 1; - this.logger.info(["┌", r("─", w-2), "┐"].join("")); + this.logger.info(["┌", r("─", w - 2), "┐"].join("")); - let printSpanTime = (span) => { + let printSpanTime = span => { let time = span.duration == null ? "?" : span.duration.toFixed(2); - let maxActionName = maxTitle - (span.level-1) * 2 - time.length - 3 - (span.fromCache ? 2 : 0) - (span.remoteCall ? 2 : 0) - (span.error ? 2 : 0); + let maxActionName = + maxTitle - + (span.level - 1) * 2 - + time.length - + 3 - + (span.fromCache ? 2 : 0) - + (span.remoteCall ? 2 : 0) - + (span.error ? 2 : 0); let actionName = span.action ? span.action.name : ""; if (actionName.length > maxActionName) actionName = _.truncate(span.action.name, { length: maxActionName }); @@ -63,27 +67,22 @@ module.exports = function() { return; } - let gstart = (span.startTime - main.startTime) / (main.endTime - main.startTime) * 100; - let gstop = (span.endTime - main.startTime) / (main.endTime - main.startTime) * 100; + let gstart = + ((span.startTime - main.startTime) / (main.endTime - main.startTime)) * 100; + let gstop = + ((span.endTime - main.startTime) / (main.endTime - main.startTime)) * 100; if (_.isNaN(gstart) && _.isNaN(gstop)) { gstart = 0; gstop = 100; } - if (gstop > 100) - gstop = 100; + if (gstop > 100) gstop = 100; - let p1 = Math.round(gw * gstart / 100); - let p2 = Math.round(gw * gstop / 100) - p1; + let p1 = Math.round((gw * gstart) / 100); + let p2 = Math.round((gw * gstop) / 100) - p1; let p3 = Math.max(gw - (p1 + p2), 0); - let gauge = [ - "[", - r(".", p1), - r("■", p2), - r(".", p3), - "]" - ].join(""); + let gauge = ["[", r(".", p1), r("■", p2), r(".", p3), "]"].join(""); this.logger.info("│ " + strAction + gauge + " │"); @@ -92,7 +91,7 @@ module.exports = function() { }; printSpanTime(main); - this.logger.info(["└", r("─", w-2), "┘"].join("")); + this.logger.info(["└", r("─", w - 2), "┘"].join("")); } }, diff --git a/examples/middlewares/index.js b/examples/middlewares/index.js index a2e48ab3..8ce49501 100644 --- a/examples/middlewares/index.js +++ b/examples/middlewares/index.js @@ -13,9 +13,9 @@ * */ -let path = require("path"); -let { ServiceBroker } = require("moleculer"); -let ApiService = require("../../index"); +let path = require("path"); +let { ServiceBroker } = require("moleculer"); +let ApiService = require("../../index"); // Create broker let broker = new ServiceBroker({ @@ -39,11 +39,13 @@ broker.createService({ whitelist: ["**"], use: [ (req, res, next) => next(new Error("Something went wrong")), - function(err, req, res, next) { - this.logger.warn("Error occured in middlewares! Terminating request and sending response"); + function (err, req, res, next) { + this.logger.warn( + "Error occured in middlewares! Terminating request and sending response" + ); res.end("Handled. No problem."); - }, - ], + } + ] } ] } diff --git a/examples/multi-auth/index.js b/examples/multi-auth/index.js index 7e3c2d61..f8579d1d 100644 --- a/examples/multi-auth/index.js +++ b/examples/multi-auth/index.js @@ -16,9 +16,9 @@ * */ -let path = require("path"); -let { ServiceBroker } = require("moleculer"); -let ApiGatewayService = require("../../index"); +let path = require("path"); +let { ServiceBroker } = require("moleculer"); +let ApiGatewayService = require("../../index"); const { UnAuthorizedError, ERR_NO_TOKEN, ERR_INVALID_TOKEN } = require("../../src/errors"); @@ -35,7 +35,6 @@ broker.createService({ mixins: [ApiGatewayService], settings: { - routes: [ { path: "/aaa", diff --git a/examples/post.service.js b/examples/post.service.js index 5b2626c9..ff0512f6 100644 --- a/examples/post.service.js +++ b/examples/post.service.js @@ -1,13 +1,13 @@ "use strict"; -const _ = require("lodash"); +const _ = require("lodash"); const { MoleculerError } = require("moleculer").Errors; -const fake = require("fakerator")(); +const fake = require("fakerator")(); function generateFakeData(count) { let rows = []; - for(let i = 0; i < count; i++) { + for (let i = 0; i < count; i++) { let item = fake.entity.post(); item.id = i + 1; item.author = fake.random.number(1, 10); @@ -36,7 +36,6 @@ module.exports = { } }, - get: { cache: { keys: ["id"] @@ -44,8 +43,7 @@ module.exports = { rest: "GET /:id", handler(ctx) { const post = this.findByID(ctx.params.id); - if (post) - return post; + if (post) return post; return Promise.reject(new MoleculerError("Post not found!", 404)); } @@ -74,12 +72,9 @@ module.exports = { handler(ctx) { const post = this.findByID(ctx.params.id); if (post) { - if (ctx.params.title) - post.title = ctx.params.title; - if (ctx.params.content) - post.content = ctx.params.content; - if (ctx.params.author) - post.author = ctx.params.author; + if (ctx.params.title) post.title = ctx.params.title; + if (ctx.params.content) post.content = ctx.params.content; + if (ctx.params.author) post.author = ctx.params.author; this.clearCache(); return post; @@ -95,7 +90,6 @@ module.exports = { this.clearCache(); } } - }, methods: { diff --git a/examples/raw/index.js b/examples/raw/index.js index 55017a57..6bb3ae7d 100644 --- a/examples/raw/index.js +++ b/examples/raw/index.js @@ -47,7 +47,7 @@ broker.createService({ aliases: { // File upload from HTML form - "POST /raw": "echo.params", + "POST /raw": "echo.params" } } ] diff --git a/examples/rest/index.js b/examples/rest/index.js index a29062ca..ccf7c4c1 100644 --- a/examples/rest/index.js +++ b/examples/rest/index.js @@ -32,9 +32,9 @@ * */ -let path = require("path"); -let { ServiceBroker } = require("moleculer"); -let ApiGatewayService = require("../../index"); +let path = require("path"); +let { ServiceBroker } = require("moleculer"); +let ApiGatewayService = require("../../index"); // Create broker let broker = new ServiceBroker({ @@ -51,22 +51,24 @@ broker.loadService(path.join(__dirname, "..", "post.service")); broker.createService({ mixins: [ApiGatewayService], settings: { - routes: [{ - // RESTful aliases - aliases: { - "REST posts": "posts" - /* + routes: [ + { + // RESTful aliases + aliases: { + "REST posts": "posts" + /* "GET posts": "posts.list", "GET posts/:id": "posts.get", "POST posts": "posts.create", "PUT posts/:id": "posts.update", "DELETE posts/:id": "posts.remove" */ - }, + }, - // Disable direct URLs (`/posts/list` or `/posts.list`) - mappingPolicy: "restrict" - }] + // Disable direct URLs (`/posts/list` or `/posts.list`) + mappingPolicy: "restrict" + } + ] } }); diff --git a/examples/routing/index.js b/examples/routing/index.js index 9c287b6f..a9f0df21 100644 --- a/examples/routing/index.js +++ b/examples/routing/index.js @@ -18,9 +18,9 @@ * GET http://localhost:3000/lang/en */ -const path = require("path"); -const { ServiceBroker } = require("moleculer"); -const ApiGatewayService = require("../../index"); +const path = require("path"); +const { ServiceBroker } = require("moleculer"); +const ApiGatewayService = require("../../index"); // Create broker const broker = new ServiceBroker(); @@ -41,24 +41,20 @@ broker.createService({ path: "/defined/", aliases: { "GET posts": "posts.list" - }, + } }, { path: "/unsecure", - whitelist: [ - "math.*" - ], + whitelist: ["math.*"] }, { path: "/generated", - whitelist: [ - "auth.*" - ], - autoAliases: true, + whitelist: ["auth.*"], + autoAliases: true }, { path: "/params", - autoAliases: true, + autoAliases: true }, { path: "/lang/:lng/", diff --git a/examples/simple/index.js b/examples/simple/index.js index da24973a..1b995b9f 100644 --- a/examples/simple/index.js +++ b/examples/simple/index.js @@ -21,9 +21,9 @@ * */ -const path = require("path"); +const path = require("path"); const { ServiceBroker } = require("moleculer"); -const ApiService = require("../../index"); +const ApiService = require("../../index"); // Create broker const broker = new ServiceBroker(); diff --git a/examples/socket.io/index.js b/examples/socket.io/index.js index 4fde1358..4918eab4 100644 --- a/examples/socket.io/index.js +++ b/examples/socket.io/index.js @@ -12,10 +12,10 @@ * */ -let path = require("path"); -let { ServiceBroker } = require("moleculer"); -let ApiGatewayService = require("../../index"); -let IO = require("socket.io"); +let path = require("path"); +let { ServiceBroker } = require("moleculer"); +let ApiGatewayService = require("../../index"); +let IO = require("socket.io"); // Create broker let broker = new ServiceBroker({ @@ -33,12 +33,14 @@ broker.createService({ mixins: [ApiGatewayService], settings: { assets: { - folder: path.join(__dirname, "assets"), + folder: path.join(__dirname, "assets") }, - routes: [{ - path: "/api" - }] + routes: [ + { + path: "/api" + } + ] }, events: { @@ -61,12 +63,17 @@ broker.createService({ this.logger.info("Client connected via websocket!"); client.on("call", ({ action, params, opts }, done) => { - this.logger.info("Received request from client! Action:", action, ", Params:", params); + this.logger.info( + "Received request from client! Action:", + action, + ", Params:", + params + ); - this.broker.call(action, params, opts) + this.broker + .call(action, params, opts) .then(res => { - if (done) - done(res); + if (done) done(res); }) .catch(err => this.logger.error(err)); }); @@ -74,7 +81,6 @@ broker.createService({ client.on("disconnect", () => { this.logger.info("Client disconnected"); }); - }); } }); diff --git a/examples/spdy/index.js b/examples/spdy/index.js index f70a138e..ff385b6e 100644 --- a/examples/spdy/index.js +++ b/examples/spdy/index.js @@ -12,11 +12,11 @@ * https://localhost:3000/hi?name=John */ -const path = require("path"); -const fs = require("fs"); -const { ServiceBroker } = require("moleculer"); -const ApiGatewayService = require("../../index"); -const spdy = require("spdy"); +const path = require("path"); +const fs = require("fs"); +const { ServiceBroker } = require("moleculer"); +const ApiGatewayService = require("../../index"); +const spdy = require("spdy"); // Create broker const broker = new ServiceBroker({ @@ -36,7 +36,7 @@ broker.createService({ // **optional** SPDY-specific options spdy: { - protocols: [ "h2", "spdy/3.1", "http/1.1" ], + protocols: ["h2", "spdy/3.1", "http/1.1"], plain: false, "x-forwarded-for": true, connection: { @@ -45,15 +45,14 @@ broker.createService({ } }, - routes: [{ - whitelist: [ - "test.hello", - "test.greeter" - ], - aliases: { - "GET hi": "test.greeter" + routes: [ + { + whitelist: ["test.hello", "test.greeter"], + aliases: { + "GET hi": "test.greeter" + } } - }] + ] }, methods: { diff --git a/examples/sse/chat.service.js b/examples/sse/chat.service.js index 4465a5af..9c3f140f 100644 --- a/examples/sse/chat.service.js +++ b/examples/sse/chat.service.js @@ -4,12 +4,12 @@ module.exports = { postMessage: { params: { message: "string", - user: "string", + user: "string" }, handler(context) { const { params } = context; context.emit("chat.sse.message", params); - }, - }, - }, + } + } + } }; diff --git a/examples/sse/index.js b/examples/sse/index.js index f3987182..8dbafbbc 100644 --- a/examples/sse/index.js +++ b/examples/sse/index.js @@ -13,14 +13,14 @@ const HOST = "0.0.0.0"; const SSE_HEADERS = { Connection: "keep-alive", "Content-Type": "text/event-stream", - "Cache-Control": "no-cache", + "Cache-Control": "no-cache" }; // Create broker const broker = new ServiceBroker({ logger: console, metrics: true, - validation: true, + validation: true }); broker.createService(ChatService); @@ -35,7 +35,7 @@ broker.createService({ ip: HOST, assets: { - folder: path.join(__dirname, "assets"), + folder: path.join(__dirname, "assets") }, routes: [ @@ -45,20 +45,17 @@ broker.createService({ "POST message": "chat.postMessage", "GET message"(request, response) { response.writeHead(200, SSE_HEADERS); - response.$service.addSSEListener( - response, - "chat.message" - ); - }, - }, - }, - ], + response.$service.addSSEListener(response, "chat.message"); + } + } + } + ] }, events: { "chat.sse*"(context) { this.handleSSE(context); - }, + } }, methods: { @@ -76,8 +73,7 @@ broker.createService({ }, addSSEListener(stream, event) { - if (!stream.write) - throw new MoleculerError("Only writable can listen to SSE."); + if (!stream.write) throw new MoleculerError("Only writable can listen to SSE."); const listeners = this.sseListeners.get(event) || new Set(); listeners.add(stream); this.sseListeners.set(event, listeners); @@ -92,7 +88,7 @@ broker.createService({ return `event: ${event}\ndata: ${JSON.stringify( data )}\nid: ${id}\nretry: ${this.sseRetry}\n\n`; - }, + } }, started() { @@ -108,7 +104,7 @@ broker.createService({ listeners.delete(listener); } } - }, + } }); // Start server diff --git a/examples/ssl/index.js b/examples/ssl/index.js index 6aae747a..0ca32e6a 100644 --- a/examples/ssl/index.js +++ b/examples/ssl/index.js @@ -19,10 +19,10 @@ * */ -let fs = require("fs"); -let path = require("path"); -let { ServiceBroker } = require("moleculer"); -let ApiService = require("../../index"); +let fs = require("fs"); +let path = require("path"); +let { ServiceBroker } = require("moleculer"); +let ApiService = require("../../index"); // Create broker let broker = new ServiceBroker({ @@ -49,10 +49,7 @@ broker.createService({ // Create a route with whitelist & body-parser { path: "/", - whitelist: [ - "math.*", - "file.image" - ], + whitelist: ["math.*", "file.image"], // Use JSON body-parser module bodyParsers: { diff --git a/examples/test.service.js b/examples/test.service.js index b2f392f0..e44a105b 100644 --- a/examples/test.service.js +++ b/examples/test.service.js @@ -92,7 +92,9 @@ module.exports = { slow(ctx) { let time = ctx.params.delay || 5000; - return this.Promise.resolve().delay(time).then(() => `Done after ${time / 1000} sec!`); + return this.Promise.resolve() + .delay(time) + .then(() => `Done after ${time / 1000} sec!`); }, wrong(ctx) { @@ -107,9 +109,12 @@ module.exports = { stream: { handler(ctx) { ctx.meta.$responseHeaders = { - "Content-Disposition": "attachment; filename=\"stream-lorem.txt\"" + "Content-Disposition": 'attachment; filename="stream-lorem.txt"' }; - const stream = fs.createReadStream(path.join(__dirname, "..", "test", "assets", "lorem.txt"), "utf8"); + const stream = fs.createReadStream( + path.join(__dirname, "..", "test", "assets", "lorem.txt"), + "utf8" + ); setTimeout(() => { stream.read(1024); }, 100); @@ -134,16 +139,16 @@ module.exports = { }, func2: { - rest : "GET /fixed/:param1/:param2", - visibility : "published", + rest: "GET /fixed/:param1/:param2", + visibility: "published", async handler(ctx) { return Promise.resolve("func2"); } }, func1: { - rest : "GET /:param1/:param2/:param3/:param4?", - visibility : "published", + rest: "GET /:param1/:param2/:param3/:param4?", + visibility: "published", async handler(ctx) { return Promise.resolve("func1"); } diff --git a/examples/webpack-vue/index.js b/examples/webpack-vue/index.js index b34d280b..62f8703e 100644 --- a/examples/webpack-vue/index.js +++ b/examples/webpack-vue/index.js @@ -20,17 +20,17 @@ * */ -let path = require("path"); -let { ServiceBroker } = require("moleculer"); -let ApiService = require("../../index"); +let path = require("path"); +let { ServiceBroker } = require("moleculer"); +let ApiService = require("../../index"); -const webpack = require("webpack"); -const devMiddleware = require("webpack-dev-middleware"); -const hotMiddleware = require("webpack-hot-middleware"); -const serveStatic = require("serve-static"); +const webpack = require("webpack"); +const devMiddleware = require("webpack-dev-middleware"); +const hotMiddleware = require("webpack-hot-middleware"); +const serveStatic = require("serve-static"); -const config = require("./webpack.config"); -const compiler = webpack(config); +const config = require("./webpack.config"); +const compiler = webpack(config); // Create broker let broker = new ServiceBroker({ @@ -46,16 +46,15 @@ broker.createService({ mixins: [ApiService], settings: { - routes: [ { path: "/api", // Action aliases aliases: { - "add": "math.add", + add: "math.add", "GET hello": "test.hello", - "GET health": "$node.health", + "GET health": "$node.health" }, // Use bodyparser modules @@ -63,7 +62,6 @@ broker.createService({ json: true, urlencoded: { extended: true } } - }, { path: "/", @@ -79,9 +77,9 @@ broker.createService({ log: broker.logger.info }), serveStatic(path.join(__dirname, "public")) - ], - }, - ], + ] + } + ] } }); diff --git a/examples/webpack-vue/webpack.config.js b/examples/webpack-vue/webpack.config.js index f9e195c0..bbc169bb 100644 --- a/examples/webpack-vue/webpack.config.js +++ b/examples/webpack-vue/webpack.config.js @@ -23,11 +23,7 @@ module.exports = { loader: "vue-loader", options: { loaders: { - "scss": [ - "vue-style-loader", - "css-loader", - "sass-loader" - ], + scss: ["vue-style-loader", "css-loader", "sass-loader"] } } }, @@ -40,23 +36,15 @@ module.exports = { }, { test: /\.scss$/, - use: [ - "vue-style-loader", - "css-loader", - "sass-loader" - ] + use: ["vue-style-loader", "css-loader", "sass-loader"] }, // this will apply to both plain `.css` files // AND `