How to use the moleculer.Errors function in moleculer

To help you get started, we’ve selected a few moleculer examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github moleculerjs / moleculer-web / examples / full / index.js View on Github external
*
 * 		First you have to login . You will get a token and set it to the `Authorization` key in header
 * 			https://localhost:4000/api/login?username=admin&password=admin
 *
 * 		Set the token to header and try again
 * 			https://localhost:4000/api/admin/~node/health
 *
 *  - File upload:
 * 		Open https://localhost:4000/upload.html in the browser and upload a file. The file will be placed to the "examples/full/uploads" folder.
 *
 */

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 ApiGatewayService = require("../../index");

// Create broker
const broker = new ServiceBroker({
	transporter: "NATS",
	metrics: true
});

// Load other services
broker.loadServices(path.join(__dirname, ".."), "*.service.js");

// Load metrics example service from Moleculer
github tiaod / moleculer-io / lib / index.js View on Github external
'use strict';

function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; }

const IO = require('socket.io');
const _ = require('lodash');

const match = require('moleculer').Utils.match;

const ServiceNotFoundError = require("moleculer").Errors.ServiceNotFoundError;

var _require = require('./errors');

const BadRequestError = _require.BadRequestError;

const chalk = require('chalk');

module.exports = {
  name: 'io',
  settings: {
    // port: 3000,
    io: {
      // options: {}, //socket.io options
      // adapter: redis({ host: 'localhost', port: 6379 }),
      namespaces: {
        '/': {
github tiaod / moleculer-io / src / index.js View on Github external
const IO = require('socket.io')
const _ = require('lodash')
const { match } = require('moleculer').Utils
const { ServiceNotFoundError } = require("moleculer").Errors;
const { BadRequestError } = require('./errors')
const chalk = require('chalk')

module.exports = {
  name: 'io',
  settings: {
    // port: 3000,
    server: true,
    io: {
      // options: {}, //socket.io options
      namespaces: {
        '/':{
          // authorization: false,
          // middlewares: [],
          // packetMiddlewares:[],
          events: {
github moleculerjs / moleculer-web / examples / auth.service.js View on Github external
/*
 * moleculer
 * Copyright (c) 2018 MoleculerJS (https://github.com/moleculerjs/moleculer)
 * MIT Licensed
 */

"use strict";

const jwt 					= require("jsonwebtoken");
const _ 					= require("lodash");
const { MoleculerError } 	= require("moleculer").Errors;

const JWT_SECRET = "TOP SECRET!!!";

// Fake user DB
const users = [
	{ id: 1, username: "admin", password: "admin", role: "admin" },
	{ id: 2, username: "test", password: "test", role: "user" }
];

/**
 * Authentication & Authorization service
 */
module.exports = {
	name: "auth",

	actions: {
github moleculerjs / moleculer-web / test / unit / errors.spec.js View on Github external
"use strict";

let errors = require("../../src/errors");
let { MoleculerClientError } = require("moleculer").Errors;

describe("Test Errors", () => {

	it("test InvalidRequestBodyError", () => {
		let err = new errors.InvalidRequestBodyError({ a: 5 }, "Problem");
		expect(err).toBeDefined();
		expect(err).toBeInstanceOf(Error);
		expect(err).toBeInstanceOf(errors.InvalidRequestBodyError);
		expect(err.code).toBe(400);
		expect(err.type).toBe("INVALID_REQUEST_BODY");
		expect(err.name).toBe("InvalidRequestBodyError");
		expect(err.message).toBe("Invalid request body");
		expect(err.data).toEqual({
			body: { a: 5 },
			error: "Problem"
		});
github moleculerjs / moleculer-web / test / services / math.service.js View on Github external
const { MoleculerError } = require("moleculer").Errors;

module.exports = {
	name: "math",
	actions: {
		add(ctx) {
			return Number(ctx.params.a) + Number(ctx.params.b);
		},

		sub(ctx) {
			return Number(ctx.params.a) - Number(ctx.params.b);
		},

		mult: {
			params: {
				a: "number",
				b: "number"
github icebob / kantab / backend / services / accounts.service.js View on Github external
"use strict";

const crypto 		= require("crypto");
const bcrypt 		= require("bcrypt");
const _ 			= require("lodash");

const jwt 			= require("jsonwebtoken");
const speakeasy		= require("speakeasy");

const DbService 	= require("../mixins/db.mixin");
const CacheCleaner 	= require("../mixins/cache.cleaner.mixin");
const ConfigLoader 	= require("../mixins/config.mixin");
const { MoleculerRetryableError, MoleculerClientError } = require("moleculer").Errors;
const C 			= require("../constants");

const HASH_SALT_ROUND = 10;

/**
 * Account service
 */
module.exports = {
	name: "accounts",
	version: 1,

	mixins: [
		DbService("accounts"),
		CacheCleaner([
			"cache.clean.accounts"
		]),
github mKeRix / room-assistant / services / election.service.js View on Github external
'use strict';

const _ = require('lodash');
const config = require('config');
const { ServiceNotFoundError, ServiceNotAvailableError } = require('moleculer').Errors;

module.exports = {
    name: 'election',

    dependencies: ['$node'],

    settings: {
        majoritySize: config.get('election.majoritySize')
    },

    events: {
        'election.leadership.request'() {
            this.updateLeadershipState();
        },

        'election.leadership.confirm'(payload) {
github moleculerjs / moleculer-apollo-server / src / service.js View on Github external
/*
 * moleculer-apollo-server
 * Copyright (c) 2019 MoleculerJS (https://github.com/moleculerjs/moleculer-apollo-server)
 * MIT Licensed
 */

"use strict";

const _ = require("lodash");
const { MoleculerServerError } = require("moleculer").Errors;
const { ApolloServer } = require("./ApolloServer");
const DataLoader = require("dataloader");
const { makeExecutableSchema } = require("graphql-tools");
const GraphQL = require("graphql");
const { PubSub, withFilter } = require("graphql-subscriptions");

module.exports = function(mixinOptions) {
	mixinOptions = _.defaultsDeep(mixinOptions, {
		routeOptions: {
			path: "/graphql",
		},
		schema: null,
		serverOptions: {},
		createAction: true,
		subscriptionEventName: "graphql.publish",
	});
github moleculerjs / moleculer-web / examples / post.service.js View on Github external
"use strict";

const _ 		= require("lodash");
const { MoleculerError } = require("moleculer").Errors;
const fake 		= require("fakerator")();

function generateFakeData(count) {
	let rows = [];

	for(let i = 0; i < count; i++) {
		let item = fake.entity.post();
		item.id = i + 1;
		item.author = fake.random.number(1, 10);

		rows.push(item);
	}

	return rows;
}