ts-db-client
TypeScript icon, indicating that this package has built-in type declarations

1.1.6 • Public • Published

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)
})

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
1.1.61latest

Version History

VersionDownloads (Last 7 Days)Published
1.1.61
1.1.50
1.1.40
1.1.20
1.1.10
1.1.00
1.0.90
1.0.80
1.0.70
1.0.60
1.0.50
1.0.40
1.0.30
1.0.20
1.0.10
1.0.00

Package Sidebar

Install

npm i ts-db-client

Weekly Downloads

1

Version

1.1.6

License

ISC

Unpacked Size

16.3 kB

Total Files

16

Last publish

Collaborators

  • varsubham