Link Search Menu Expand Document

🥦 Simple but Awesome TypeScript DI Framework for Node.js 🥦

build:? coverage:? license:mit downloads:? node:?

Table of contents

Tarpit is a Dependency Injection (DI) Framework, built-on TypeScript. As a platform, we can build reusable, testable and maintainable applications on it.

Simply, Tarpit collects services and puts them where you declare them by specifying the constructor parameter type.

Get more -> What is Tarpit

We have built three out-of-the-box modules for benefit:

Installation

To use Tarpit framework you should be familiar with the following:

Assuming you’ve already installed Node.js and TypeScript, create a directory to hold your application, and make that your working directory.

$ mkdir myapp
$ cd myapp

Use the npm init command to create a package.json file for your application. For more information on how package.json works, see Specifics of npm’s package.json handling.

$ npm init -y

Use the tsc init command to create a tsconfig.json file for your application. For more information on how tsconfig.json works, see Intro to the TSConfig Reference.

$ tsc init

To use decorators and get the parameters’ metadata, we should enable options experimentalDecorators and emitDecoratorMetadata.

// tsconfig.json
{
    // ...
    "experimentalDecorators": true,
    /* Enable experimental support for TC39 stage 2 draft decorators. */
    "emitDecoratorMetadata": true
    /* Emit design-type metadata for decorated declarations in source files. */
    // ...
}

We need to install the http package and its peer dependencies for primary usage.

$ npm install @tarpit/http $(node -p "Object.keys($(npm view @tarpit/http peerDependencies)).join(' ')")

Command node -p "Object.keys($(npm view @tarpit/core peerDependencies)).join(' ')" figure out the peer dependencies and consist them to space separate string.

Hello World

As a pure DI Framework doesn’t include any functional component, we do this with HTTP Server Module:

import {Platform} from '@tarpit/core'
import {HttpServerModule, TpRouter, Get} from '@tarpit/http'

@TpRouter('/', {imports: [HttpServerModule]})
class FirstRouter {
    @Get()
    async hello() {
        return 'Hello World!'
    }
}

const platform = new Platform({http: {port: 3000}})
        .import(FirstRouter)
        .start()

The above code declares a router with base URL '/', and an API with suffix 'hello-world'. After that, it creates a Platform instance and loads HttpServerModule and FirstRouter, and finally starts it.

For every other path, it will respond with a 404 Not Found.

To start, you can use tsc to compile it to JavaScript and run it by node ./index.js.

Or directly use ts-node ./index.ts.

$ ts-node ./index.ts
# Tarpit server started at 2022-XX-XXTXX:XX:XX.XXXZ, during 0.001s

Let’s test the API with the following code:

$ curl -X GET 'http://localhost:3000/hello'
# Hello World!

Next steps

Guess you want to know about these things