1.1.6 • Published 7 months ago

ts-db-client v1.1.6

Weekly downloads
-
License
ISC
Repository
github
Last release
7 months ago

ts-db-client

npm version install size npm downloads

Simple Wrapper Library over DB clients. Currently Supports PostgreSQL, MYSQL. Other DBMS support coming soon.

Installing

Using npm:

$ npm install ts-db-client

Example

import { PGClient } from 'ts-db-client'

Default test DB Config

import { PGClient } from 'ts-db-client'

// initialize a default PG DB client
    /**
     * host:      "localhost"
     * userName:  "postgres"
     * password:  "admin"
     * port:       5432
     * database:  "postgres"
    **/
const pgClient = PGClient.defaultConfig()


// Create a User DTO to map users table columns 
// (if not mapped than default values will be used)
class User {
    id: number = 0
    handle: string = ""
}

// fetch<T> return single row
pgClient.fetch<User>('SELECT * FROM users WHERE id = $1', new User(), [2])
    .then((res) => {
        console.log(res)
    })
    .catch((err) => {
        console.error(err)
})

Fetch multiple Rows from DB(map Rows to a DTO)

// Create a DTO for Data mapping
class User {
    id: number = 0
    handle: string = ""
}

// fetchAll will return multiple rows
// The data will be mapped to User DTO as User[]
pgClient.fetchAll<User>('SELECT * FROM users', new User())
    .then((res) => {
        console.log(res)
    })
    .catch((err) => {
        console.error(err)
})

Fetch All Using 1 fieldName

NOTE: If you want to return multiple rows only one row name, then we can use this method You donot need to create a DTO

// Create a DTO for Data mapping
class User {
    id: number = 0
    handle: string = ""
}

// fetchAllUsingField will return multiple fields
// but we can query using a fieldName.
// Below we are returning data using 'handle'
pgClient.fetchAllUsingField<string>('select handle from users', "handle")
    .then((res: number[]) => {
        console.log(res)
    })
    .catch((err) => {
        console.log(err)
})

Fetch All Using 2 fieldName

NOTE: If you want to return multiple rows using only two row fieldName, then we can use this method You donot need to create a DTO

// Create a DTO for Data mapping
class User {
    id: number = 0
    handle: string = ""
}

// fetchAll will return multiple rows
// The data will be mapped to User DTO as User[]
pgClient.fetchAllUsingTwoFields<number, string>('select id, handle from users', "id", "handle")
    .then((res) => {
        console.log(res)
    })
    .catch((err) => {
        console.log(err)
})
1.1.6

7 months ago

1.1.1

9 months ago

1.1.5

9 months ago

1.1.4

9 months ago

1.1.2

9 months ago

1.1.0

2 years ago

1.0.9

2 years ago

1.0.8

2 years ago

1.0.7

2 years ago

1.0.6

2 years ago

1.0.5

2 years ago

1.0.4

2 years ago

1.0.3

2 years ago

1.0.2

2 years ago

1.0.1

2 years ago

1.0.0

2 years ago