Blog

  • stencil

    Stencil Template Engine

    Stencil is an open source templating engine that transforms Office Open XML documents (mostly Microsoft Office’s Word .docx files) from the JVM. It has a simple syntax and no programming is needed to write document templates.

    stencil flow

    You can use either Microsoft Word or LibreOffice to edit the document templates. The template expressions are just simple textual expressions, and you can even colour-code them to make your template more readable.

    Clojars Project CI codecov contributions welcome

    Hits EPL 2.0

    Features

    • 📄 Multiple Formats: Works with docx and pptx files
    • 💻 Simple syntax: For value substitution, conditional and repeating blocks
    • 🔧 Extendable: Dozens of built-in functions callable from the template
    • 📰 Dynamic content: Substituting HTML text for dynamic text formatting
    • 🌄 Images and links: Dynamically replace images and links in the template
    • 👀 Tables: Show/hide rows and columns in tables
    • 📐 Programmable: Offers API for Java and Clojure. Deployable as a Docker container.

    📖 Getting Started with the Library

    🐳 Getting Started with the Service

    The project has a simple service implementation, which is available on GitHub Packages as a Container image.

    👉 Version

    Latest stable version is 0.6.3

    Latest snapshot version is 0.6.4-SNAPSHOT

    Previous versions are available on the Stencil Clojars page.

    For Java with Maven

    If you are using Maven, add the followings to your pom.xml:

    1. The dependency:
    <dependency>
      <groupId>io.github.erdos</groupId>
      <artifactId>stencil-core</artifactId>
      <version>0.6.3</version>
    </dependency>
    1. And the Clojars repository:
    <repository>
      <id>clojars.org</id>
      <url>https://repo.clojars.org</url>
    </repository>
    For Java with Gradle

    Add to the dependencies section of your build.gradle file: implementation('io.github.erdos/stencil-core:0.6.3')

    For Clojure with Leiningen

    If you are using Leiningen, add the following to the :dependencies section of your project.clj file:

    [io.github.erdos/stencil-core "0.6.3"]

    For Clojure with deps.edn

    Add io.github.erdos/stencil-core {:mvn/version "0.6.3"}

    😎 License

    Copyright (c) Janos Erdos. All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public License 2.0 (https://www.eclipse.org/legal/epl-2.0/) which can be found in the file LICENSE.txt at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.

    Visit original content creator repository https://github.com/erdos/stencil
  • stencil

    Stencil Template Engine

    Stencil is an open source templating engine that transforms Office Open XML documents (mostly Microsoft Office’s Word .docx files) from the JVM. It has a simple syntax and no programming is needed to write document templates.

    stencil flow

    You can use either Microsoft Word or LibreOffice to edit the document templates. The template expressions are just simple textual expressions, and you can even colour-code them to make your template more readable.

    Clojars Project CI codecov contributions welcome

    Hits EPL 2.0

    Features

    • 📄 Multiple Formats: Works with docx and pptx files
    • 💻 Simple syntax: For value substitution, conditional and repeating blocks
    • 🔧 Extendable: Dozens of built-in functions callable from the template
    • 📰 Dynamic content: Substituting HTML text for dynamic text formatting
    • 🌄 Images and links: Dynamically replace images and links in the template
    • 👀 Tables: Show/hide rows and columns in tables
    • 📐 Programmable: Offers API for Java and Clojure. Deployable as a Docker container.

    📖 Getting Started with the Library

    🐳 Getting Started with the Service

    The project has a simple service implementation, which is available on GitHub Packages as a Container image.

    👉 Version

    Latest stable version is 0.6.3

    Latest snapshot version is 0.6.4-SNAPSHOT

    Previous versions are available on the Stencil Clojars page.

    For Java with Maven

    If you are using Maven, add the followings to your pom.xml:

    1. The dependency:
    <dependency>
      <groupId>io.github.erdos</groupId>
      <artifactId>stencil-core</artifactId>
      <version>0.6.3</version>
    </dependency>
    1. And the Clojars repository:
    <repository>
      <id>clojars.org</id>
      <url>https://repo.clojars.org</url>
    </repository>
    For Java with Gradle

    Add to the dependencies section of your build.gradle file: implementation('io.github.erdos/stencil-core:0.6.3')

    For Clojure with Leiningen

    If you are using Leiningen, add the following to the :dependencies section of your project.clj file:

    [io.github.erdos/stencil-core "0.6.3"]

    For Clojure with deps.edn

    Add io.github.erdos/stencil-core {:mvn/version "0.6.3"}

    😎 License

    Copyright (c) Janos Erdos. All rights reserved. The use and distribution terms for this software are covered by the Eclipse Public License 2.0 (https://www.eclipse.org/legal/epl-2.0/) which can be found in the file LICENSE.txt at the root of this distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice, or any other, from this software.

    Visit original content creator repository https://github.com/erdos/stencil
  • WaktuSolatAPI

    WaktuSolatAPI

    A free, unlimited, custom request API. Data were crawled from www.e-solat.gov.my. The data are available for all states in Malaysia for year 2017.

    You can use the API by using URL below:
    www.mardyoe.com/waktusolat/api/date.php

    Parameters

    Variable Description
    zone* Zone code
    start Start date for a range date (Y-m-d). Remove if want to return today’s prayer times
    end End date for a range date (Y-m-d)
    format 12-hour or 24-hour time format
    pre Display in pre tag (true) or display in json format (false)

    Note: * is a mandatory parameter

    Usage Example

    http://www.mardyoe.com/waktusolat/api/date.php?zone=ktn01&start=2017-01-01&end=2017-01-01&format=12-hour&pre=true
    

    Result

    Array
    (
        [zone] => KTN01
        [state] => KELANTAN
        [district] => Kota Bharu, Bachok, Pasir Puteh, Tumpat, Pasir Mas, Tnh. Merah, Machang, Kuala Krai, Mukim Chiku
        [start] => 2017-01-01
        [end] => 2017-01-01
        [prayer_times] => Array
            (
                [0] => Array
                    (
                        [date] => 2017-01-01
                        [imsak] => 5:54 AM
                        [subuh] => 6:04 AM
                        [syuruk] => 7:22 AM
                        [zohor] => 1:17 PM
                        [asar] => 4:38 PM
                        [maghrib] => 7:09 PM
                        [isyak] => 8:20 PM
                    )
            )
    )
    

    Additional Contributor

    Thanks to:

    • Ariff Yasri – Scrapping the data

    Motivation

    Before this API is available to use, there are hard to get a prayer times for a specific time range. There are might have, but the data is not up-to-date, available only for today, and limited number of query per day.

    Visit original content creator repository
    https://github.com/zarulizham/WaktuSolatAPI

  • Discord-Bot-Lists

    Discord Bot list’s

    This list features every botlist out there that is working as of now. This repo is automatically updated every day.

    Botlists:

    Name Website Discord Ping Status
    Wumpus.store Website Discord Invite 1ms 🟢
    Top.gg Website Discord Invite 3ms 🟢
    Discord bot list Website Discord Invite 6ms 🟢
    Discord-botlist.eu Website Discord Invite 2ms 🟢
    Void Bots Website Discord Invite 3ms 🟢
    Discords Website Discord Invite 30ms 🟢
    Botlist Website Discord Invite 3ms 🟢
    Discord Bots Website Discord Invite 9ms 🟢
    Infinity Bot list Website Discord Invite 2ms 🟢
    Stellar Bot list Website Discord Invite 5ms 🟢
    Rovel Discord List Website Discord Invite 2ms 🟢
    Blist Website Discord Invite 2ms 🟢
    Radar Cord Website Discord Invite 4ms 🟢
    Const Eagle Website Discord Invite 1ms 🟢
    Bladelist Website Discord Invite 4ms 🟢
    Discordz Website Discord Invite 7ms 🟢
    Fates List Website Discord Invite 0ms 🔴
    Discord List Website Discord Invite 11ms 🟢
    Discord Services Website Discord Invite 4ms 🟢
    Discord Labs Website Discord Invite 11ms 🟢
    Vipercord Website Discord Invite 0ms 🔴
    B.H Botlist Website Discord Invite 0ms 🔴
    Bots on Discord Website Discord Invite 6ms 🟢
    DiscordBots Website NONE 3ms 🟢
    There is a Bot for that Website NONE 0ms 🔴
    TopCord Website Discord Invite 2ms 🟢
    Yet Another Bot List Website Discord Invite 1ms 🟢
    Carbonitex Website Discord Invite 1ms 🟢
    Discord Bot App Website Discord Invite 3ms 🟢
    Discord Extreme List Website Discord Invite 1ms 🟢
    Disforge Website Discord Invite 2ms 🟢
    Motion Development Website NONE 32ms 🟢
    VCodes Website Discord Invite 2ms 🟢
    Wonder Bot List Website Discord Invite 15ms 🟢
    Vitallist Website Discord Invite 3ms 🔴
    Universe List Website Discord Invite 88ms 🟢

    If you got a botlist that you want to add here simply open a pull request and it will be here as soon as possible!

    Contributors

    CloneRepo

    Visit original content creator repository https://github.com/mezotv/Discord-Bot-Lists
  • viuavm

    Viua VM Latest Release

    builds.sr.ht status CII Best Practices

    License

    A register-based, parallel virtual machine programmable in custom assembly lookalike language with strong emphasis on reliability, predictability, and concurrency.

    Building the code

    ]$ ./configure      # (1) configure the project
    ]$ make -j          # (2) build it
    

    Calling ./configure is not required if you do not want or need to run tests under Valgirnd. Configuring will create necessary suppresion file for your version of Valgrind.

    Note: the default build is run with -O0 (without any optimisations). You can compile Viua VM with higher optimisation leves, but keep in mind that the compilation might not succeed on machines with less than 4GB RAM if you use the -O3 optimisation level.

    This is tracked by issue 7c06177872c3a718510a54e6513820f8fe0fb99b in the embedded issue repository.

    Hello World in Viua VM

    .function: main/0
        allocate_registers %3 local
    
        text %1 local "Hello World!\n"
        integer %2 local 1
    
        io_write %2 local %2 local %1 local
        io_wait void %2 local 1s
    
        izero %0 local
        return
    .end
    

    See README.asm file to see commented version of this sample program.

    For more examples visit either documentation or Rosetta page for Viua VM. Check Weekly blog for news and developments in Viua VM.

    Use cases

    Viua is a runtime environment focused on reliability, predictability, and concurrency. It is suitable for writing long-running software that runs in the background providing infrastructure services:

    • servers (e.g. IRC)
    • message queues
    • system and application daemons (e.g. cron)

    The VM is not ready to be used in places where performance matters. It is best to employ it for tasks which do not require human interaction or near real-time responses.

    The VM should be able to fully utilise all cores of the CPU it’s running on to execute the virtual processes and FFI calls of the software it runs. If configured to do so it may generate high CPU loads, but is relatively light on RAM and should not contain any memory leaks (all runtime tests are run under Valgrind to ensure this).

    The virtual machine is covered by more than 500 tests to provide safety, and guard against possible regressions. It ships with an assembler and a static analyser, but does not provide any higher-level language compiler or debugger.


    Design goals

    • predictable execution: it is easier to reason about code when you know exactly how it will behave
    • predictable value lifetimes: in Viua you do not have to guess when the memory will be released, when objects will be destroyed, or remember about the possibility of a gargabe collector kicking in and interrupting your program. Viua manages resources without a GC in a strictly scope-based (where “scope” means “virtual stack frame”) manner
    • massive concurrency: Viua architecture supports spawning massive amounts of independent, VM-based lightweight processes that can run in parallel (Viua is capable of providing true parallelism given sufficient hardware resources, i.e. at least two physical CPU cores)
    • parallel I/O and FFI schedulers: I/O operations and FFI calls cannot block the VM as they are executed on dedicated schedulers, so block only the virtual process that called them without affecting other virtual processes
    • easy scatter/gather processing: processes communicate using messages but machine supports a join instruction – which synchronises virtual processes execution, it blocks calling process until called process finishes and receives return value of called process
    • safe inter-process communication via message-passing (with queueing)
    • soft-realtime capabilities: it is possible to set a timeout on process joins, message receives, and all I/O operations. It should make Viua a VM suitable to host soft-realtime programs that need to provide some timing guarantees
    • fast debugging: error handling is performed with exceptions (even across virtual processes), and unserviced exceptions cause the machine to generate precise and detailed stack traces
    • reliability: programs running on Viua should be able to run until they are told to stop, not until they crash; machine helps writing reliable programs by providing a framework for detailed exception-based error communication and a way to register a per-process watchdog that handles processes killed by runaway exceptions (the exception is serviced by watchdog instead of killing the whole VM)

    Some features also supported by the VM:

    • separate compilation of Viua code modules
    • static and dynamic linking of Viua-native libraries
    • straightforward ways to use both dynamic and static function call dispatch
    • first-class functions
    • closures (with multiple way of capturing objects inside a closure)
    • passing function parameters by value, by move (non-copying pass), and by pointer
    • copy-free function returns
    • inter-function tail calls
    • several variants of fixed-size integer arithmetic: wrapping, checked, and saturating

    For enhanced reliability, Viua assembler provides a built-in static analyser that is able to detect most common errors related to register manipulation at compile time (type mismatches, invalid register access). It provides traced errors whenever possible, i.e. when it detects an error and is able to trace execution path that would trigger it, a sequence of instructions (with source code locations) leading to the detected error is presented to the user instead of a single offending instruction.

    Current limitations include:

    • severly limited introspection
    • calling Viua code from C++ is not tested
    • debugging information encoded in compiled files is limited
    • speed: Viua is not the fastest VM around
    • lack of libraries
    Software state notice

    Viua VM is an alpha-stage software.

    Even though great care is taken not to introduce bugs during development, it is inevitable that some will make their way into the codebase. Viua in its current state is not production ready; bytecode definition and format will be altered, opcodes may be removed and added without deprecation warning, and various external and internal APIs may change without prior notice.

    Suitable announcements will be made when the VM reaches beta, RC and release stages.

    Influences

    The way Viua works has mostly been influenced by C++ (static and dynamic method dispatch, move semantics), and Erlang (message passing, indepenedent VM-based lightweight processes as units of concurrency).


    Programming in Viua

    Viua can be programmed in an assembly-like language which must be compiled into bytecode. A typical session is shown below (assuming current working directory is the local clone of Viua repository):

     ]$ vim some_file.asm
     ]$ ./build/bin/vm/asm -o some_file.bc some_file.asm
    # static analysis or syntax errors...
     ]$ vim some_file.asm
     ]$ ./build/bin/vm/asm -o some_file.bc some_file.asm
     ]$ ./build/bin/vm/kernel some_file.bc
    # runtime exceptions...
     ]$ vim some_file.asm
     ]$ ./build/bin/vm/asm -o some_file.bc some_file.asm
     ]$ ./build/bin/vm/kernel some_file.bc
    

    Contributing

    Please read CONTRIBUTING.markdown for details on development setup, and the process for submitting patches, bug reports, and feature suggestions.

    Issues are tracked using the Issue tool.

    Patches should be submitted via email. See “Contact information” at the bottom of this file.

    The code can be cloned either from Savannah or from Sourcehut.


    License

    The code is licensed under GNU GPL v3.


    Contact information

    Project website: viuavm.org

    Maintainer: <marekjm at ozro dot pw>

    Visit original content creator repository https://github.com/marekjm/viuavm
  • react-hooks-v8

    react-hooks-v8

    Description
    The “react-hooks-v8” project is a collection of examples and experiments showcasing the usage of various React hooks such as useRef, useId, useCallback, useLayoutEffect, useMemo, and useReducer. Each hook is implemented in a separate file, with dedicated routes in the application to demonstrate its functionality and usage. The project serves as a learning resource for understanding how these hooks work and how they can be effectively used in React applications.

    Features

    • Dedicated routes for each React hook implementation.
    • Examples demonstrating the usage and benefits of useRef, useId, useCallback, useLayoutEffect, useMemo, and useReducer.
    • Clear explanations and comments in each file to aid understanding.
    • Built with React and Vite for efficient development and fast bundling.

    Technologies Used

    • Frontend: React, Vite
    • Routing: React Router
    • Styling: CSS Modules
    • Version Control: Git, GitHub

    Three.js Integration

    The “react-hooks-v8” project also incorporates Three.js, a JavaScript library used for creating and displaying 3D graphics in a web browser. Three.js enhances the visual experience of the application by enabling the rendering of complex 3D scenes and animations directly within the React components. Leveraging Three.js opens up possibilities for creating immersive and interactive user interfaces, making it an ideal choice for projects requiring advanced visualization capabilities.

    Installation
    Clone the repository:

    git clone https://github.com/Srushti-9/react-hooks-v8.git

    Install dependencies:

    cd react-hooks-v8
    npm install

    Start the development server:

    npm run dev

    Usage

    Once the development server is running, navigate to the localhost URL provided in the terminal. From there, you can explore the different routes corresponding to each React hook implementation.

    Visit original content creator repository
    https://github.com/Srushti-9/react-hooks-v8

  • mac-hid-dump

    mac-hid-dump

    mac-hid-dump is a small command-line app to output the HID Report Descriptors of all connected HID devices. Think of it as sort of a MacOS version of usbhid-dump. It is designed to inspect HID devices for use with hidapi, node-hid, or similar HID libraries. The output can be parsed directly by the USB Descriptor Parser.

    mac-hid-dump uses some of the Mac-specific code from libusb/hidapi, a cross-platform library for communicating with HID devies. It is not dependent on hidapi though.

    Usage:

    To use mac-hid-dump, download the zip file from the Releases page, unzip it, and run it.

    When run, its output looks like the below.

    tod@demo ~/Downloads/mac-hid-dump$ ./mac-hid-dump
    mac-hid-dump:
    16C0 0486:  - Teensyduino RawHID Device
    DESCRIPTOR:
      06  c9  ff  09  04  a1  5c  75  08  15  00  26  ff  00  95  40
      09  75  81  02  95  20  09  76  91  02  95  04  09  76  b1  02
      c0
      (33 bytes)
    16C0 0486:  - Teensyduino RawHID Device
    DESCRIPTOR:
      06  ab  ff  0a  00  02  a1  01  75  08  15  00  26  ff  00  95
      40  09  01  81  02  95  40  09  02  91  02  c0
      (28 bytes)
    27B8 01ED: ThingM - blink(1) mk3
    DESCRIPTOR:
      06  ab  ff  0a  00  20  a1  01  15  00  26  ff  00  75  08  85
      01  95  08  09  00  b2  02  01  75  08  85  02  95  3c  09  00
      b2  02  01  c0
      (36 bytes)
    tod@demo ~/Downloads/mac-hid-dump$
    
    

    This example shows a
    Teensy RawHID and a blink(1) USB LED. The Teensy RawHID descriptor shows a simple “RawHID” example of a single 64-byte report using no reportIDs for both Input and Output. The blink(1) descriptor shows an example that defines two reportID-based Feature reports: an 8-byte one and a 60-byte one.

    Visit original content creator repository
    https://github.com/todbot/mac-hid-dump

  • elasticsearch-russian-phonetics

    Elasticsearch plugin for Russian Phonetic Analysis

    Build Status Code Coverage for encoder project License Apache%202.0 blue

    This plugin provides phonetic analysis of Russian language by exposing russian_phonetic token filter which transforms russian words to their phonetic representation or so-called phonetic code. These codes are used for matching words and names which sound similar. The process of transformation is also known as phonetic encoding and this plugin is able to encode millions of russian words per second with the lowest impact on GC among all encoders compared in encoding throughput benchmarks.

    Encoding algorithm extensively employs phonetic and orthographic rules in order to fill the inconsistency gap between spelling and pronunciation in Russian Language.

    Examples of spelling and pronunciation inconsistency
    вдры[зг]        ⟷    вдры[ск]
    слове[тск]ий    ⟷    славе[цк]ий
    ла[ндш]афт      ⟷    ла[нш]афт
    п[я]так         ⟷    п[и]так
    бу[хг]алтер     ⟷    бу[г]алтер
    бю[стг]алтер    ⟷    бю[зд]галтер
    ле[стн]ица      ⟷    ле[сн]ица
    кислово[дск]    ⟷    кислово[цк]

    You can find more information about encoding process at the encoding rules and unit tests.

    Installation

    In order to install the plugin, choose a version and run:

    $ bin/elasticsearch-plugin install URL

    where URL points to zip file of the appropriate release which corresponds to your elasticsearch version.

    The plugin must be installed on every node in the cluster, and each node must be restarted after installation.

    E.g., command for Elasticsearch 7.6.2

    # install plugin on Elasticsearch 7.6.2
    $ bin/elasticsearch-plugin install https://github.com/papahigh/elasticsearch-russian-phonetics/raw/7.6.2/esplugin/plugin-distributions/analysis-russian-phonetic-7.6.2.zip

    After installation plugin exposes new token filter named russian_phonetic.

    Getting started

    You can start using the russian_phonetic token filter by providing analysis configuration:

    PUT /russian_phonetic_sample
    {
      "settings": {
        "analysis": {
          "analyzer": {
            "my_analyzer": {
              "tokenizer": "standard",
              "filter": [
                "standard",
                "russian_phonetic"
              ]
            }
          },
          "filter": {
            "russian_phonetic": {
              "type": "russian_phonetic",
              "replace": false
            }
          }
        }
      }
    }

    Then you should be able to hit the analyzer with russian_phonetic token filter using the analyze API

    POST /russian_phonetic_sample/_analyze
    {
      "analyzer": "my_analyzer",
      "text": "студентка комсомолка спортсменка"
    }

    Returns: стднк, студентка, кмсмлк, комсомолка, спрцмнк, спортсменка

    Token filter settings

    The russian_phonetic token filter provides a bunch of configuration options to meet your particular needs:

    replace

    Whether or not the original token should be replaced by the phonetic code. Accepts true (default) or false.

    vowels

    Defines encoding mode for vowels. Accepts encode_first (default) or encode_all.

    encode_first: only first vowel in the supplied word will be encoded
    упячка          → упчк
    голландский     → глнскй
    абсурд          → апсрт
    encode_all: all vowels will be encoded according to the encoding rules
    упячка          → уп2чк1
    голландский     → г1л1нск2й
    абсурд          → апс3рт
    max_code_len

    The maximum length of the phonetic code. Defaults to 8.

    enable_stemmer

    Whether or not the stemming should be applied. Accepts true or false (default). When this option is enabled only base (or root) form of the supplied word will be encoded.

    аннотируешь     → антрш
    аннотируешься   → антрш
    аннотируешь     → ан1т2р32ш
    аннотируешься   → ан1т2р32ш
    ящурным         → ящрн
    ящурные         → ящрн
    ящурным         → ящ3рн
    ящурные         → ящ3рн
    💡
    Please take a look at the throughput and distribution benchmarks to be aware of encoder’s behaviour and performance under certain options value.

    Credits

    Contribute

    Use the issue tracker and/or open pull requests.

    Licence

    Both encoder and esplugin projects are released under version 2.0 of the Apache Licence.

    Visit original content creator repository https://github.com/papahigh/elasticsearch-russian-phonetics
  • ts_injector

    Typescript Injector

    Simple and lightweight injector for typescript projects.


    Installation

    npm install @xeinebiu/ts_injector@1.0.2

    Modules

    Module allows you to provide classes when they are requested via injection

    createDiModule({
        provides: [{
            provide: FeedRepository
        }]
    })

    On the example above, we are providing FeedRepository on any scope required.

    Now, to use it, simply annotate the property with @Inject()

    class Demo {
        
        @Inject()
        private readonly feedRepository!: FeedRepository
    }

    Providers

    Singleton

    To make the FeedRepository a singleton, simply add singleton: true

    FeedReposiotory class must not be abstract

    createDiModule({
        provides: [{
            provide: FeedRepository,
            singleton: true
        }]
    })

    Use Class

    Whether your project is built in on abstraction, the following example can be used.

    createDiModule({
        provides: [{
            singleton: true,
            provide: FeedRepository,    // can also be abstract when used with `useClass`
            useClass: DemoFeedRepository
        }]
    })

    DemoFeedRepository will be provided for FeedRepository. Since we are setting singleton: true, a single instance is shared.

    Use Value

    Provide a class instance for requested provider.

    createDiModule({
        provides: [{
            provide: FeedRepository,    // can also be abstract when used with `useValue`
            useValue: new DemoFeedRepository(...arguments)
        }]
    })

    When useValue is used, singleton is set by default to true


    Scope

    Using scope allows providing different classes on specific scope.

    createDiModule({
        provides: [{
            provide: FeedRepository,
            useClass: RootFeedRepository,
            provideIn: 'root'
        }]
    })

    It is a must to annotate the class where the scope is needed.

    @Scope({
        scope: 'root'
    })
    class RootDemo {
    
        @Inject()
        private readonly feedRepository!: FeedRepository
    }

    feedRepository on RootDemo is provided with RootFeedRepository

    Visit original content creator repository https://github.com/xeinebiu/ts_injector
  • ts_injector

    Typescript Injector

    Simple and lightweight injector for typescript projects.


    Installation

    npm install @xeinebiu/ts_injector@1.0.2

    Modules

    Module allows you to provide classes when they are requested via injection

    createDiModule({
        provides: [{
            provide: FeedRepository
        }]
    })

    On the example above, we are providing FeedRepository on any scope required.

    Now, to use it, simply annotate the property with @Inject()

    class Demo {
        
        @Inject()
        private readonly feedRepository!: FeedRepository
    }

    Providers

    Singleton

    To make the FeedRepository a singleton, simply add singleton: true

    FeedReposiotory class must not be abstract

    createDiModule({
        provides: [{
            provide: FeedRepository,
            singleton: true
        }]
    })

    Use Class

    Whether your project is built in on abstraction, the following example can be used.

    createDiModule({
        provides: [{
            singleton: true,
            provide: FeedRepository,    // can also be abstract when used with `useClass`
            useClass: DemoFeedRepository
        }]
    })

    DemoFeedRepository will be provided for FeedRepository. Since we are setting singleton: true, a single instance is shared.

    Use Value

    Provide a class instance for requested provider.

    createDiModule({
        provides: [{
            provide: FeedRepository,    // can also be abstract when used with `useValue`
            useValue: new DemoFeedRepository(...arguments)
        }]
    })

    When useValue is used, singleton is set by default to true


    Scope

    Using scope allows providing different classes on specific scope.

    createDiModule({
        provides: [{
            provide: FeedRepository,
            useClass: RootFeedRepository,
            provideIn: 'root'
        }]
    })

    It is a must to annotate the class where the scope is needed.

    @Scope({
        scope: 'root'
    })
    class RootDemo {
    
        @Inject()
        private readonly feedRepository!: FeedRepository
    }

    feedRepository on RootDemo is provided with RootFeedRepository

    Visit original content creator repository https://github.com/xeinebiu/ts_injector