Git Product home page Git Product logo

rxdi / core Goto Github PK

View Code? Open in Web Editor NEW
11.0 4.0 1.0 1.66 MB

This repository is archived and moved to Monorepo https://github.com/rxdi/rxdi-monorepo/tree/master/packages/core

TypeScript 96.27% JavaScript 3.73%
rxjs reactive-programming reactive-extension dependency-injection-container dependency-injection-framework dependency-injection typescript typescript-decorators typescript-framework observable-streams

core's Introduction

Powerful Dependency Injection inside Browser and Node using Typescript and RXJS 6


The idea behind @rxdi is to create independent, dependency injection that can be used everywhere, Node and Browser with purpose also to share the same code without chainging nothing! First steps where with platform called @gapi you can check repository @gapi/core. Then because of the needs of the platform i decided to develop this Reactive Dependency Injection container helping me build progressive applications. Hope you like my journey! Any help and suggestions are appreciated! Main repository @rxdi/core


Example starter projects:

Client Side

Client Side Advanced

Server Side

More examples for @rxdi infrastructure you can check inside @gapi namespace.

@Beta Decentralized node_modules using ipfs network with rxdi infrastructure

Install @rxdi/core global so we will have rxdi command available npm i -g @rxdi/core

Install single decentralized ipfs module rxdi install QmWtJLqyokMZE37DgncpY5HhFvtFQieBzMPDQ318aJeTw6

More details you can find here ipfs-package-example

Example module https://ipfs.io/ipfs/QmWtJLqyokMZE37DgncpY5HhFvtFQieBzMPDQ318aJeTw6

@rxdi/core can be found also inside decentralized space here

@rxdi/core can be installed with '@rxdi/core' total inception :D rxdi i QmP9n7m1UWkFn2hqt7mnfQYnBtxmFyyvKZHN7hgngQb1gM

No more package downtime!

Installation and basic examples:

To install this library, run:
npm install @rxdi/core

Simplest app

main.ts

import { Bootstrap } from '@rxdi/core';
import { AppModule } from './app/app.module';

Bootstrap(AppModule, {
    init: false, // if init is false you can set specifically which parts of the system should initialize their constructors
    initOptions: {
        services: true,
        components: true,
        effects: true,
        controllers: true,
        plugins: true,
        pluginsAfter: true,
        pluginsBefore: true
    },
    logger: {
        logging: true,
        date: true,
        hashes: true,
        exitHandler: true,
        fileService: true
    }
})
.subscribe(
    () => console.log('App Started!'),
    (err) => console.error(err)
);

app.module.ts

import { Module } from "@rxdi/core";
import { UserModule } from './user/user.module';

@Module({
    imports: [UserModule]
})
export class AppModule {}

user.module.ts

import { Module } from '@rxdi/core';
import { UserService } from './services';
import { Observable } from 'rxjs';

@Module({
    services: [
        UserService,
        {
            provide: 'createUniqueHash',
            useDynamic: {
                fileName: 'createUniqueHash',
                namespace: '@helpers',
                extension: 'js',
                typings: '',
                outputFolder: '/node_modules/',
                link: 'https://ipfs.infura.io/ipfs/QmdQtC3drfQ6M6GFpDdrhYRKoky8BycKzWbTkc4NEzGLug'
            }
        },
        {
            provide: 'testFactoryAsync',
            lazy: true,
            useFactory: async () => {
                return new Promise((resolve) => {
                    setTimeout(() => resolve('dad2a'), 0);
                })
            }
        },
        {
            provide: 'testFactorySync',
            useFactory: () => {
                return 'dada';
            }
        },
        {
            provide: 'testValue2',
            useValue: 'dadada'
        },
        {
            provide: 'testChainableFactoryFunction',
            // lazy: true, if you don't provide lazy parameter your factory will remain Observable so you can chain it inside constructor
            useFactory: () => new Observable(o => o.next(15))
        },
    ]
})
export class UserModule {}

user.service.ts

import { Service, Inject } from "@rxdi/core";
import { Observable } from "rxjs";
import { map } from "rxjs/operators";

@Service()
export class UserService {
    constructor(
        @Inject('createUniqueHash') private ipfsDownloadedFactory: { testKey: () => string },
        @Inject('testFactoryAsync') private testFactoryAsync: { testKey: () => string },
        @Inject('testChainableFactoryFunction') private chainableFactory: Observable<number>

    ) {
        console.log('UserService', this.ipfsDownloadedFactory.testKey(), this.testFactoryAsync);
        this.chainableFactory
            .pipe(
                map((res) => res)
            )
            .subscribe(value => console.log('Value chaining factory ', value));

    }
}

Result

1529604446114 Bootstrap -> @Module('AppModule')(adb785e839fa19736cea0920cd39b783): loading...
1529604446116 Bootstrap -> @Module('UserModule')(9ed4f039657f52019d2d9adb0f9df09f): loading...
1529604446118 Bootstrap -> @Module('UserModule')(9ed4f039657f52019d2d9adb0f9df09f): finished!
1529604446118 Bootstrap -> @Module('AppModule')(adb785e839fa19736cea0920cd39b783): finished!
1529604446119 Bootstrap -> @Service('createUniqueHash'): loading...
1529604446121 Bootstrap -> @Service('createUniqueHash'): will be downloaded inside ./node_modules/@helpers/createUniqueHash.js folder and loaded from there
1529604446121 Bootstrap -> @Service('createUniqueHash'): https://ipfs.infura.io/ipfs/QmdQtC3drfQ6M6GFpDdrhYRKoky8BycKzWbTkc4NEzGLug downloading...
1529604446137 Bootstrap -> @Service('testFactoryAsync'): loading...
1529604446146 Bootstrap -> @Service('testFactoryAsync'): loading finished! 21:07:26
1529604446795 Done!
1529604446797 Bootstrap: @Service('createUniqueHash.js'): Saved inside /home/rampage/Desktop/concept-starter/node_modules/@helpers
1529604446808 Bootstrap -> @Service('createUniqueHash'): loading finished! 21:07:26
1529604446810 Done!
1529604446811 Bootstrap: @Service('createUniqueHash.js'): Saved inside /home/rampage/Desktop/concept-starter/node_modules/@helpers
1529604446812 Bootstrap -> press start!
1529604446813 Start -> @Module('UserModule')(9ed4f039657f52019d2d9adb0f9df09f): @Service('UserService')(ea785b316b77dbfe5cb361a7cdcbcb31) initialized!
UserService TestKey dad2a
Value chaining factory  15
1529604446813 Start -> @Module('UserModule')(9ed4f039657f52019d2d9adb0f9df09f): loaded!
1529604446813 Start -> @Module('AppModule')(adb785e839fa19736cea0920cd39b783): loaded!
Started!
AppStopped

ForRoot configuration for modules

import { Module, ModuleWithServices, InjectionToken } from '@rxdi/core';

@Service()
export class MODULE_DI_CONFIG {
    text: string = 'Hello world';
}


export const MY_MODULE_CONFIG = new InjectionToken<MODULE_DI_CONFIG>('my-module-config');


@Module({
  imports: []
})
export class YourModule {
  public static forRoot(config?: any): ModuleWithServices {
    return {
      module: YourModule,
      services: [
          { provide: MY_MODULE_CONFIG, useValue: { text: 'Hello world' } },
          { provide: MY_MODULE_CONFIG, useClass: MODULE_DI_CONFIG },
          { 
            provide: MY_MODULE_CONFIG,
            useFactory: () => {
                return {text: 'Hello world'};
            }
          },
          {
            provide: 'ipfsDownloadableFactory',
            useDynamic: {
                fileName: 'createUniqueHash',
                namespace: '@helpers',
                extension: 'js',
                typings: '',
                outputFolder: '/node_modules/',
                link: 'https://ipfs.infura.io/ipfs/QmdQtC3drfQ6M6GFpDdrhYRKoky8BycKzWbTkc4NEzGLug'
            }
          }
      ],
      components: [],
      frameworkImports: []
    }
  }
}

Parcel

Inside @gapi/cli package there is a command called gapi start --local --parcel this command will run @gapi or @rxdi application with parcel there is a also command called gapi build which will take src/main.ts and will bundle it the same way like parcel build src/main.ts --target node

To install @gapi/cli type:

npm i -g @gapi/cli

Start with @gapi/cli

gapi start --local --parcel

Build with @gapi/cli

gapi build

Or you can install Parcel globally and use instead of @gapi/cli

Install Parcel:

npm install -g parcel-bundler

Build single bundle from first bootstrapped file in this case main.ts

parcel build src/main.ts --target node

This command will generate single file from this application inside dist/main.js with mappings dist/main.map

Starting bundled application

node ./dist/main.js

Important!

This will not bundle your node modules only rxdi application.

If you want to start app with ts-node for example you need to set inside tsconfig.json -> compilerOptions: {}

{
    "compilerOptions": {
        "emitDecoratorMetadata": true,
        "experimentalDecorators": true
    }
}

Possible pattern with @rxdi/core

import { setup } from '@rxdi/core';
import { switchMap } from 'rxjs/operators';
import { combineLatest } from 'rxjs';

setup({
  services: [
    {
      provide: 'gosho',
      lazy: true,
      useFactory: async () => 'yey'
    }
  ]
})
  .pipe(
    switchMap(ctx =>
      combineLatest(
        setup({
          services: [
            {
              provide: 'pesho',
              useFactory: () => (ctx as any).get('gosho')
            }
          ]
        }),
        setup({
          services: []
        }),
        setup({
          services: []
        }),
        setup({
          services: []
        })
      )
    )
  )
  .subscribe(ctx => {
    console.log((ctx as any).get('pesho'));
  });

core's People

Contributors

stradivario avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

Forkers

tamebadger

core's Issues

reduce core DI bundle size - ideas

Hi, i think its possible to get the core (DI only) bundle size down by about 1000% with a little effort. This will certainly have to happen in the future, so it's better to address it now imo.

check out https://github.com/jmankopf/mani-injector and replace 'reflect-metadata' with @abraham/reflection. works great. (like 300 loc vs rxdi 40k lol).

jupyter lab has a light weight DI system with similar semantics as rxdi , except without decorators. I think it uses bottlejs under the hood.

Also,
I also did a quick test without getting it actually working, removing the ipfs and systemjs stuff from rxdi and got it down to around 7k loc, which that alone could be a good start.

https://github.com/jeffijoe/awilix also is pretty great because it doesn't require any reflection polyfill, and works in the browser by dropping 2 fs methods, which could be kept and swapped for an ipfs solution.

awilix + rxjs container/di
https://github.com/mojzu/container.ts/blob/master/src/container/container.ts

Thought/solution generation and comparison only atm

bug(Plugins): when no register method is provided throws unhandled error

This error is leading to missunderstanding of what is happening with the platform in this period of time

Provided this plugin

import { Inject, Plugin } from '@rxdi/core';
import { HAPI_SERVER } from '@rxdi/hapi';
import { Server } from 'hapi';

@Plugin()
export class ServeComponents {
  constructor(@Inject(HAPI_SERVER) private server: Server) {}

}

Throws error

TypeError: plugin.register is not a function
    at BootstrapService.<anonymous> (/home/rampage/Desktop/work/repos/public/graphql-server-from-json/node_modules/@rxdi/core/dist/services/bootstrap/bootstrap.service.js:147:26)
    at Generator.next (<anonymous>)
    at /home/rampage/Desktop/work/repos/public/graphql-server-from-json/node_modules/@rxdi/core/dist/services/bootstrap/bootstrap.service.js:16:71
    at new Promise (<anonymous>)
    at __awaiter (/home/rampage/Desktop/work/repos/public/graphql-server-from-json/node_modules/@rxdi/core/dist/services/bootstrap/bootstrap.service.js:12:12)
    at BootstrapService.registerPlugin (/home/rampage/Desktop/work/repos/public/graphql-server-from-json/node_modules/@rxdi/core/dist/services/bootstrap/bootstrap.service.js:145:16)
    at BootstrapService.<anonymous> (/home/rampage/Desktop/work/repos/public/graphql-server-from-json/node_modules/@rxdi/core/dist/services/bootstrap/bootstrap.service.js:118:94)
    at Generator.next (<anonymous>)
    at /home/rampage/Desktop/work/repos/public/graphql-server-from-json/node_modules/@rxdi/core/dist/services/bootstrap/bootstrap.service.js:16:71
    at new Promise (<anonymous>)
    at __awaiter (/home/rampage/Desktop/work/repos/public/graphql-server-from-json/node_modules/@rxdi/core/dist/services/bootstrap/bootstrap.service.js:12:12)
    at pluginService.getPlugins.filter.map (/home/rampage/Desktop/work/repos/public/graphql-server-from-json/node_modules/@rxdi/core/dist/services/bootstrap/bootstrap.service.js:118:29)
    at Array.map (<anonymous>)
    at BootstrapService.asyncChainablePluginsRegister (/home/rampage/Desktop/work/repos/public/graphql-server-from-json/node_modules/@rxdi/core/dist/services/bootstrap/bootstrap.service.js:118:18)
    at SwitchMapSubscriber.rxjs_1.combineLatest.pipe.operators_1.switchMap [as project] (/home/rampage/Desktop/work/repos/public/graphql-server-from-json/node_modules/@rxdi/core/dist/services/bootstrap/bootstrap.service.js:59:554)
    at SwitchMapSubscriber._next (/home/rampage/Desktop/work/repos/public/graphql-server-from-json/node_modules/rxjs/internal/operators/switchMap.js:49:27)

Correct situation

import { Inject, Plugin } from '@rxdi/core';
import { HAPI_SERVER } from '@rxdi/hapi';
import { Server } from 'hapi';

@Plugin()
export class ServeComponents {
  constructor(@Inject(HAPI_SERVER) private server: Server) {}

  async register() {
    this.server.route({
        method: 'GET',
        path: '/devtools/{param*}',
        handler: {
          directory: {
            path: `${__dirname.replace('dist/services', '')}/public`,
            index: ['index.html', 'default.html']
          }
        }
      });
  }

}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.