What is the correct way to integrate knex using inversify?

Is there a way for me to set up knex and utilize the Inversify dependency injector to inject it wherever it is required?

Answer №1

Although I haven't had the opportunity to work with Knex, I am the creator of InversifyJS and I am willing to assist you.

According to the Knex documentation, you can set it up in the following manner:

var knex = require('knex')({
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
});

I've also located the TypeScript types for Knex here.

If you wish to inject the knex instance, you could do the following:

import * as Knex from 'knex';
import { Kernel } from "inversify";

// configuration
let configuration: Knex.Config = {
  client: 'mysql',
  connection: {
    host : '127.0.0.1',
    user : 'your_database_user',
    password : 'your_database_password',
    database : 'myapp_test'
  }
};

// instance
let knex: Knex = Knex(configuration);

let kernel = new Kernel();
kernel.bind<Knex>("Knex").toConstantValue(knex);

To make the knex a singleton, the approach above can be used. If a singleton is not desired, a factory can be implemented as follows:

 import * as Knex from 'knex';
 import { interfaces, Kernel } from "inversify";

 kernel.bind<interfaces.Factory<Knex>>("Factory<Knex>")
       .toFactory((ctx: interfaces.Context) => {
           return Knex({
               client: 'mysql',
               connection: {
                   host : '127.0.0.1',
                   user : 'your_database_user',
                   password : 'your_database_password',
                   database : 'myapp_test'
               }
           });
       });

Another option is to separate the configuration like so:

 import * as Knex from 'knex';
 import { interfaces, Kernel } from "inversify";

 kernel.bind<Knex.Config>("KnexConfig").toConstantValue({
     client: 'mysql',
     connection: {
         host : '127.0.0.1',
         user : 'your_database_user',
         password : 'your_database_password',
         database : 'myapp_test'
     }
 });

 kernel.bind<interfaces.Factory<Knex>>("Factory<Knex>")
       .toFactory((ctx: interfaces.Context) => {
           let config = context.kernel.get<Knex.Config>("KnexConfig");
           return Knex(config);
       });

These methods provide a factory for creating the knex instance:

let knexFactory = kernel.get<interfaces.Factory<Knex>>("Factory<Knex>");
let knex = knexFactory();

The factory can be injected into other classes using an @inject("Factory<Knex>") annotation.

If using a singleton or factory is not preferred, dynamic value injection can be utilized:

kernel.bind<Knex>("Knex").toDynamicValue((context: interfaces.Context) => {
    return Knex({
        client: 'mysql',
        connection: {
            host : '127.0.0.1',
            user : 'your_database_user',
            password : 'your_database_password',
            database : 'myapp_test'
        }
    });
});

This dynamic value injection approach will provide a new knex instance each time, neither a singleton nor a factory:

let knex = kernel.get<Knex>("Knex>");

Please bear in mind that these suggestions have not been tested. I hope they point you in the right direction.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing a d.ts Typescript Definition file for enhanced javascript intellisene within projects not using Typescript

I am currently working on a TypeScript project where I have set "declaration": true in tsconfig.json to generate a d.ts file. The generated d.ts file looks like this: /// <reference types="jquery" /> declare class KatApp implements IKatApp ...

Exploring the wonders of Angular 2: Leveraging NgbModal for transclusion within

If I have a modal template structured like this: <div class="modal-header"> <h3 [innerHtml]="header"></h3> </div> <div class="modal-body"> <ng-content></ng-content> </div> <div class="modal-footer"& ...

Oops! Looks like there was an issue with assigning to a reference or variable: Error: Uncaught (in promise)

I seem to be struggling with an issue that I believe may have been addressed before, but after reviewing other solutions, I am unable to pinpoint the error in my code. Any assistance in identifying my mistake would be greatly appreciated. <div class="j ...

What are the steps for integrating Angularfire2 into an Angular application?

Trying to integrate Angularfire2 into a fresh Angular project, but encountered an issue while following the official documentation. This is the guide I followed Upon reaching step 7 - Inject AngularFirestore, console errors were displayed: https://i.sst ...

Exploring Ionic 4 with Angular Router

Presently, I am working on developing an application using the latest beta version 4 of Ionic and implementing the tabs layout. I am still trying to grasp how the navigation works with the new Angular router. This is my app-routing.module.ts: import { N ...

Tips for utilizing ion-img within an Ionic 3 application?

I am currently developing an app using Ionic 3 that includes a large number of images spread across different pages. Initially, I used the default HTML image tag to display these images. However, this approach caused lag in the app's performance and a ...

Tips for ensuring that the code inside a subscribe block completes before moving on to the next iteration within a forEach loop in Angular

Within the code snippet below, there exists a for loop where an API call is made. The intention is to have the 1st API call complete and execute all the subscribed code before moving on to the next iteration of the loop, triggering another API call. Curre ...

An issue arises in Typescript when attempting to pass an extra prop through the server action function in the useForm

I am struggling with integrating Next.js server actions with useFormState (to display input errors on the client side) and Typescript. As per their official documentation here, they recommend adding a new prop to the server action function like this: expo ...

Using an array of references in React

I've encountered a problem where I'm trying to create a ref array from one component and then pass it to another inner component. However, simply passing them as props to the inner component doesn't work as it returns null. I attempted to fo ...

Discovering a solution to extract a value from an Array of objects without explicitly referencing the key has proven to be quite challenging, as my extensive online research has failed to yield any similar or closely related problems

So I had this specific constant value const uniqueObjArr = [ { asdfgfjhjkl:"example 123" }, { qwertyuiop:"example 456" }, { zxcvbnmqwerty:"example 678" }, ] I aim to retrieve the ...

The push() method replaces the last item in an array with another item

Two objects are available: ej= { name="", code: "", namebusinessG:"", codebusinessG:"" }; group = { name:"", code:"" } Both of these objects will be stored in two arrays: groupList:any[]=[]; ejList:any[]=[]; The program flow s ...

Guide to setting data types for [key, value] pairs within a forEach iteration

I am currently encountering a typescript syntax error in my project that is indicating the need to define the prodStatus variable... const products = { 1: {isUpdating: false, qty: 2}, 2: {isUpdating: true, qty: 4} } const updatingProducts: Array< ...

Is there a way to specify patternProperties in a JSON schema and then map it to a TypeScript interface?

I'm in the process of developing a TypeScript interface that corresponds to a JSON schema. The specific field in my JSON schema is as follows: "styles": { "title": "Style Definitions", &qu ...

Ways to Access HTTP Request Headers in Angular 6 upon Page Load

Is it possible to retrieve request header information in Angular 6/7 upon application initialization? I specifically require access to header values for security and access management purposes, as these values are set in the headers during the usage of th ...

Issue with Angular not sending data to ASP.net server

Attempting to send data to my asp.net server using angular. After testing the front-end data, the issue arises when sending the data with a post request; angular sends null data instead. Interestingly, when sending the same data to the server from Postman, ...

NextJS API Generator for OpenAPI specifications

In my NextJS project, we utilize the /api path to implement our API, with an openapi.yaml file defining the interface. To generate the API client successfully, we run the following command: openapi-generator-cli generate -i data/api/openapi.yaml -o src/api ...

How to showcase the data retrieved via BehaviorSubject in Angular

I've been working on retrieving data from an API using a service and passing it to components using BehaviorSubject in order to display it on the screen: Here is the service code snippet: @Injectable({ providedIn: 'root', }) export clas ...

Having trouble getting Angular 8 WebRTC to function properly on two tabs

I've been tasked with creating an audio chat room for 2 users. Initially, I used the following app example: Peer connection: audio only After converting the code to TypeScript, it successfully ran: Stackblitz However, I'm facing challenges ge ...

Updating the variable in Angular 6 does not cause the view to refresh

I am facing an issue with my array variable that contains objects. Here is an example of how it looks: [{name: 'Name 1', price: '10$'}, {name: 'Name 2', price: '20$'}, ...] In my view, I have a list of products bei ...