moleculerjs / moleculer-template-project-typescript Goto Github PK
View Code? Open in Web Editor NEWTypescript project template for Moleculer microservices framework.
License: MIT License
Typescript project template for Moleculer microservices framework.
License: MIT License
The debug process is not working with this template. Im using this project in lerna workspace but its not working
Can you please add a sample launch.json file?
Here is my current launch config.
"type": "node",
"request": "launch",
"name": "Launc",
"program": "${workspaceRoot}/node_modules/moleculer/bin/moleculer-runner.js",
"args": [
"${workspaceRoot}/packages/backend/services/**/**/*.service.ts",
"--env"
],
"sourceMaps": true,
"trace": "all",
"env": {
"PORT": "3000"
},
"preLaunchTask": "npm: build - packages/backend",
"cwd": "${workspaceRoot}",
"outFiles": ["${workspaceRoot}/packages/backend/dist/**/**/*.js"]
}
Here is my task file
"version": "2.0.0",
"tasks": [
{
"type": "npm",
"script": "build",
"path": "packages/backend/",
"group": "build",
"problemMatcher": [],
"label": "npm: build - packages/backend",
"detail": "tsc --build tsconfig.json && cp .env ./dist/.env "
}
]
}
ERROR: moleculer.config.ts:6:3 - trailing whitespace
ERROR: moleculer.config.ts:8:3 - trailing whitespace
ERROR: moleculer.config.ts:10:36 - trailing whitespace
ERROR: moleculer.config.ts:11:61 - trailing whitespace
ERROR: moleculer.config.ts:14:3 - trailing whitespace
ERROR: moleculer.config.ts:15:107 - trailing whitespace
ERROR: moleculer.config.ts:16:116 - trailing whitespace
ERROR: moleculer.config.ts:17:1 - Exceeds maximum line length of 120
ERROR: moleculer.config.ts:28:2 - The key 'logLevel' is not sorted alphabetically
ERROR: moleculer.config.ts:34:24 - trailing whitespace
ERROR: moleculer.config.ts:41:25 - trailing whitespace
ERROR: moleculer.config.ts:42:83 - trailing whitespace
ERROR: moleculer.config.ts:56:3 - The key 'delay' is not sorted alphabetically
ERROR: moleculer.config.ts:65:1 - Exceeds maximum line length of 120
ERROR: moleculer.config.ts:73:1 - Exceeds maximum line length of 120
ERROR: moleculer.config.ts:86:32 - trailing whitespace
ERROR: moleculer.config.ts:90:3 - The key 'preferLocal' is not sorted alphabetically
ERROR: moleculer.config.ts:100:3 - The key 'minRequestCount' is not sorted alphabetically
ERROR: moleculer.config.ts:114:3 - The key 'concurrency' is not sorted alphabetically
ERROR: moleculer.config.ts:129:1 - Exceeds maximum line length of 120
ERROR: moleculer.config.ts:134:1 - Exceeds maximum line length of 120
ERROR: moleculer.config.ts:141:18 - block is empty
ERROR: moleculer.config.ts:146:18 - block is empty
ERROR: moleculer.config.ts:151:18 - block is empty
ERROR: services/greeter.service.ts:65:12 - block is empty
Please answer the following questions for yourself before submitting an issue.
When I turn on strict mode in tsconfig.json, with
"strict": true
I get an error on some of the broker options. A few of them are simple null -> undefined changes needed, but I did run into one that I believe is a problem in the type definition of CheckRetryable
:
type CheckRetryable = (err: Error) => boolean;
This causes the Typescript to error out:
src/moleculer.broker.config.ts:52:3 - error TS2322: Type '{ check: (err: Errors.MoleculerRetryableError) => boolean; delay: number; enabled: false; factor: number; maxDelay: number; retries: number; }' is not assignable to type 'RetryPolicyOptions'.
Types of property 'check' are incompatible.
Type '(err: Errors.MoleculerRetryableError) => boolean' is not assignable to type 'CheckRetryable'.
Types of parameters 'err' and 'err' are incompatible.
Type 'Error' is missing the following properties from type 'MoleculerRetryableError': code, type, data, retryable
52 retryPolicy: {
~~~~~~~~~~~
Typescript compilation should work in strict mode. I believe the fix is to fix the type of CheckRetryable
:
type CheckRetryable = (err: Errors.MoleculerRetryableError) => boolean;
tsconfig.json
Please provide any relevant information about your setup. This is important in case the issue is not reproducible except for under certain conditions.
Hi
I have a problem with this db mixin template .
the schema initalized in private field so the event name be undefined ;
I just replace it in constructor statement and problem solved .
Greetings.
I'm using the "dev" configuration from the package.json (using moleculer-runner) using Moleculer version 0.13.13 (TypeScript). I have the following code in moleculer.config.ts (excerpt):
...
created: async (broker: ServiceBroker) => {
broker.logger.error("CREATED");
},
started: async (broker: ServiceBroker) => {
broker.logger.error("STARTED");
},
...
Except of adding these functions I also added NATS configuration of 3 options, and it works.
When I run npm run dev, these functions are not called, and I don't see those messages (and any other code there won't run).
Debugging through the code led me to the node_modules/moleculer/src/service-broker.js@348
, where I can see this code:
...
.then(() => {
if (_.isFunction(this.options.started))
return this.options.started(this);
});
Under debugger it says that this.options.started is undefined, while this.options.brokerConfig includes this "started" event (and "created" as well).
When I run it without moleculer-runner, e.g. using jest in tests, creating broker with const broker = new ServiceBroker(brokerConfig);
, these methods are there and they are being called and run.
How to make it call these "created" and "started" events on the broker using moleculer-runner? Thank you.
Hi, at the moment it seems like there is no way to override the type for this
parameter for the lifecycle methods (created
, started
and stopped
). In consequence, it's impossible to create those methods if they implement a custom this
(similarly to how methods and actions do it).
This can be temporarily ignored as suggested in #67, but that's a workaround and not a fix.
I'm realtively new to typescript so I might be missing some obvious solution / best practices related to this, but I think the following could work:
index.d.ts
// ...
type ServiceSyncLifecycleHandler<S = ServiceSettingSchema> = (this: Service<S>) => void;
type ServiceAsyncLifecycleHandler<S = ServiceSettingSchema> = (this: Service<S>) => void | Promise<void>;
interface ServiceSchema<S = ServiceSettingSchema> {
name: string;
version?: string | number;
settings?: S;
dependencies?: string | ServiceDependency | (string | ServiceDependency)[];
metadata?: any;
actions?: ServiceActionsSchema;
mixins?: Partial<ServiceSchema>[];
methods?: ServiceMethods;
hooks?: ServiceHooks;
events?: ServiceEvents;
created?: ServiceSyncLifecycleHandler<S> | ServiceSyncLifecycleHandler<S>[];
started?: ServiceAsyncLifecycleHandler<S> | ServiceAsyncLifecycleHandler<S>[];
stopped?: ServiceAsyncLifecycleHandler<S> | ServiceAsyncLifecycleHandler<S>[];
[name: string]: any;
}
// ...
should be changed to:
index.d.ts
// ...
type ServiceSyncLifecycleHandler<S = ServiceSettingsSchema, T = Service<S>> = (this: T) => void;
type ServiceAsyncLifecycleHandler<S = ServiceSettingSchema, T = Service<S>> = (this: T) => void | Promise<void>;
interface ServiceSchema<S = ServiceSettingSchema, T = void> {
name: string;
version?: string | number;
settings?: S;
dependencies?: string | ServiceDependency | (string | ServiceDependency)[];
metadata?: any;
actions?: ServiceActionsSchema;
mixins?: Partial<ServiceSchema>[];
methods?: ServiceMethods;
hooks?: ServiceHooks;
events?: ServiceEvents;
created?: ServiceSyncLifecycleHandler<S, T> | ServiceSyncLifecycleHandler<S, T>[];
started?: ServiceAsyncLifecycleHandler<S, T> | ServiceAsyncLifecycleHandler<S, T>[];
stopped?: ServiceAsyncLifecycleHandler<S, T> | ServiceAsyncLifecycleHandler<S, T>[];
[name: string]: any;
}
// ...
The above code is meant to provide a way to supply additional type for this
parameter at the service declaration level (e.g. in greeter.service.ts), which would change it from:
export interface GreeterSettings extends ServiceSettingSchema {
defaultName: string;
}
export interface GreeterMethods {
uppercase(str: string): string;
}
export type GreeterThis = Service<GreeterSettings> & GreeterMethods;
const GreeterService: ServiceSchema<GreeterSettings> = {
name: "greeter",
settings: {
defaultName: "Moleculer",
},
dependencies: [],
actions: {},
events: {},
methods: {
uppercase(str: string) {
return str.toUpperCase()();
},
},
created(this: GreeterThis) { // <-- This does not work
console.log(this.broker.services);
},
async started(this: GreeterThis){ // <-- This does not work
this.uppercase('hello world');
},
async started(this: GreeterThis){ // <-- This does not work
this.uppercase('goodbye world');
},
};
to
export interface GreeterSettings extends ServiceSettingSchema {
defaultName: string;
}
export interface GreeterMethods {
uppercase(str: string): string;
}
export type GreeterThis = Service<GreeterSettings> & GreeterMethods;
const GreeterService: ServiceSchema<GreeterSettings, GreeterThis> = { // <-- This is the actual change
// in service declaration
name: "greeter",
settings: {
defaultName: "Moleculer",
},
dependencies: [],
actions: {},
events: {},
methods: {
uppercase(str: string) {
return str.toUpperCase()();
},
},
created(this: GreeterThis) {
console.log(this.broker.services);
},
async started(this: GreeterThis){
this.uppercase('hello world');
},
async started(this: GreeterThis){
this.uppercase('goodbye world');
},
};
Please let me know if you'd like me to create a PR with this change.
In test case Test hooks (see https://github.com/moleculerjs/moleculer-template-project-typescript/blob/master/template/test/unit/services/products.spec.ts#L145-L180 ), products
service was modified by broker.createService()
function with fake create action.
Expect
createActionFn
products
service be modified by mods objectActual
createActionFn
products
service be not modified by mods objectReason
In broker.createService()
function source code (see https://github.com/moleculerjs/moleculer/blob/master/src/service-broker.js#L794-L813 ), I see:
When create products
service, it in case 1 because ProductsService
is extend of Service
. But in constructor
method, ProductsService
don't process schema argument like Service
class.
Fix
I fixed by below code. Anyone have a better idea?
import {Context, Service, ServiceBroker, ServiceSchema} from "moleculer";
import DbConnection from "../mixins/db.mixin";
export default class ProductsService extends Service{
private DbMixin = new DbConnection("products").start();
// @ts-ignore
public constructor(public broker: ServiceBroker, schema: ServiceSchema<{}> = {}) {
super(broker);
this.parseServiceSchema(Service.mergeSchemas({
// default schema
}));
}
// ...
}
Hi faeron,
can I add it to moleculer organization as typescript project template?
I think I found a solution to the started()
and stopped()
methods:
That currently shows the following problem:
Type '() => void' is not assignable to type '() => Bluebird<void>'. Type 'void' is not assignable to type 'Bluebird<void>'.
The problem is in Moleculer's index.d.ts
that requires returning a Bluebird promise
started?: () => Bluebird<void>;
stopped?: () => Bluebird<void>;
Because of this the only way to declare the started
and stopped
is
started() {
return this.Promise.resolve() // this.Promise is a reference to Bluebird promise
}
However, it should be possible to use native promises and async/await. To make it work
index.d.ts
must be updated as follows:
started?: () => PromiseLike<void>;
stopped?: () => PromiseLike<void>;
With PromiseLike
the compiler will accept anything that looks like a promise.
@faeron @icebob I think this change won't break anything but I'm not sure because I'm a complete newbie in Typescript
Hi, I have a problem with debuging.
Error: Could not read source map for {filePath}/node_modules/typescript/lib/typescript.js: ENOENT: no such file or directory, open '{filePath}/node_modules/typescript/lib/typescript.js.map'
Please help me check it!
I used .vscode following https://github.com/moleculerjs/moleculer-template-project-typescript/blob/master/template/.vscode/launch.json
services/api.service.ts:78:5 - error TS2322: Type '{ path: string; whitelist: string[]; use: never[]; mergeParams: true; authentication: false; authorization: false; autoAliases: true; aliases: {}; callingOptions: {}; bodyParsers: { json: { strict: false; limit: string; }; urlencoded: { ...; }; }; mappingPolicy: "all"; logging: true; }' is not assignable to type 'ApiRouteSchema'. Object literal may only specify known properties, but 'callingOptions' does not exist in type 'ApiRouteSchema'. Did you mean to write 'callOptions'?
78 callingOptions: {},
After running moleculer init project-typescript projectname
, when trying to run the project using npm run dev, I am getting above error.
Here are my configuration when setting up project.
? Add API Gateway (moleculer-web) service? (Y/n) Y
? Add API Gateway (moleculer-web) service? Yes
? Would you like to communicate with other nodes? (Y/n) Y
? Would you like to communicate with other nodes? Yes
? Select a transporter (Use arrow keys)
? Select a transporter NATS (recommended)
? Would you like to use cache? (y/N) N
? Would you like to use cache? No
? Add DB sample service? (Y/n) n
? Add DB sample service? No
? Would you like to enable metrics? (Y/n) n
? Would you like to enable metrics? No
? Would you like to enable tracing? (Y/n) n
? Would you like to enable tracing? No
? Add Docker & Kubernetes sample files? (Y/n) Y
? Add Docker & Kubernetes sample files? Yes
? Use ESLint to lint your code? (Y/n) Y
? Use ESLint to lint your code? Yes
Create 'mlclr-broken' folder...
? Would you like to run 'npm install'? (Y/n) Y
? Would you like to run 'npm install'? Yes
Using your npm run dev command, I get the following error:
Not supported file extension: .ts Error: Not supported file extension: .ts
at loadConfigFile (/home/gsibble/apps/moleculertest/node_modules/moleculer/bin/moleculer-runner.js:148:35)
at tryCatcher (/home/gsibble/apps/moleculertest/node_modules/bluebird/js/release/util.js:16:23)
at Promise._settlePromiseFromHandler (/home/gsibble/apps/moleculertest/node_modules/bluebird/js/release/promise.js:512:31)
at Promise._settlePromise (/home/gsibble/apps/moleculertest/node_modules/bluebird/js/release/promise.js:569:18)
at Promise._settlePromise0 (/home/gsibble/apps/moleculertest/node_modules/bluebird/js/release/promise.js:614:10)
at Promise._settlePromises (/home/gsibble/apps/moleculertest/node_modules/bluebird/js/release/promise.js:693:18)
at Async._drainQueue (/home/gsibble/apps/moleculertest/node_modules/bluebird/js/release/async.js:133:16)
at Async._drainQueues (/home/gsibble/apps/moleculertest/node_modules/bluebird/js/release/async.js:143:10)
at Immediate.Async.drainQueues (/home/gsibble/apps/moleculertest/node_modules/bluebird/js/release/async.js:17:14)
at runCallback (timers.js:794:20)
at tryOnImmediate (timers.js:752:5)
at processImmediate [as _immediateCallback] (timers.js:729:5)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] dev: ts-node ./node_modules/moleculer/bin/moleculer-runner.js --hot --repl --config moleculer.config.ts services/**/*.service.ts
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm ERR! A complete log of this run can be found in:
npm ERR! /home/gsibble/.npm/_logs/2018-09-26T18_17_45_500Z-debug.log
I was able to narrow it down. This command runs fine:
ts-node ./node_modules/moleculer/bin/moleculer-runner.js --hot --repl services/**/*.service.ts
But adding the config with the ts extension breaks it:
ts-node ./node_modules/moleculer/bin/moleculer-runner.js --hot --repl --config moleculer.config.ts services/**/*.service.ts
Am I doing something wrong or what should I do?
Hello,
yesterday i've started using moleculer and i've tried to generate a typescript project with
moleculer init project-typescript ts-moleculer-project
Info:
macOS Catalina
Version 10.15.2
npm 6.9.0
These following things i chosed:
After that, cd project,** npm install** and npm run dev.
But i've got an error caused by missing nats dependencies.
file: moleculer.config.ts
in BrokerConfig Object property transporter is not set correctly i think.
After setting to TCP everything is fine
delete this sorry
Hi,
after generating the project with project-typescript
template and running npm run test
I'm getting errors. Most of them I managed to solve as they were just syntax issues, but one bothers me and I can't figure out what's the problem.
FAIL test/unit/services/products.spec.ts
● Test 'products' service › Test hooks › Test before 'create' hook › should add quantity with zero
expect(jest.fn()).toBeCalledTimes(expected)
Expected number of calls: 1
Received number of calls: 0
179 | });
180 |
> 181 | expect(createActionFn).toBeCalledTimes(1);
| ^
182 | expect(createActionFn.mock.calls[0][0].params).toEqual({
183 | id: "111",
184 | name: "Test product",
at test/unit/services/products.spec.ts:181:32
at fulfilled (test/unit/services/products.spec.ts:5:58)
When I debug it, the method is called with corect values. But when testing it says it's not. I was also trying to debug the parseServiceSchema
and I can't find there where the hooks are applied to the service so I can't really test if the mock function is correctly assigned. Any idea what is the solution?
TSLint is on security fixes only and will no longer be maintained a year from now.
When installing the 'moleculer-template-project-ts' project, following the instructions contained in that repo, using the current moleculer-cli, I encounter this error:
Running 'npm install'...
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: rosterboss@undefined
npm ERR! Found: [email protected]
npm ERR! node_modules/eslint
npm ERR! dev eslint@"^7.2.0" from the root project
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer eslint@"^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0" from [email protected]
npm ERR! node_modules/eslint-plugin-sonarjs
npm ERR! dev eslint-plugin-sonarjs@"^0.5.0" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
npm ERR!
npm ERR! See /Users/ken/.npm/eresolve-report.txt for a full report.
I am dealing with this template to implement the authenticate stuff with "methods" property.
The isssue is that i got a sintax error.
If I correct the syntax:
I dont know how to do to pass the flow for this piece of code.
I can implement my login/jwttoken with "beforeCall", but I want to do with the moleculer way of do the things.
Is it possible to get the broker?
@faeron could you upgrade this template to Moleculer v0.14?
It's not just dependencies upgrade, you should upgrade moleculer.config.js & meta.json, new products service, public folder...etc
Here is a list of changes from JS template: https://github.com/moleculerjs/moleculer-template-project/pull/19/files
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.