1.0.37 • Published 9 months ago

m2tk v1.0.37

Weekly downloads
-
License
MIT
Repository
-
Last release
9 months ago

MySQL to TypeScript Knex

Generates TypeScript types for Knex.js using MySQL tables.

Getting started

Create knexfile.js:

module.exports = {
  client: 'mysql2',
  connection: {
    host: '127.0.0.1',
    port: 3306,
    database: 'db',
    user: 'user',
    password: 'password',
    charset: 'utf8mb4',
  },
};

Run:

npx m2tk --prefix=Db > src/db/DbTypes.ts

You can put the command into your package.json scripts section:

{
  "scripts": {
    "types": "m2tk --prefix=Db > src/core/services/DbTypes.ts"
  }
}

This command will generate DbTypes.ts with contents like:

import { Knex } from 'knex';

export interface DbUser {
  id: number;
  createdAt: Date;
  username: string;
  password: string;
}

export class DB {
  constructor(public readonly knex: Knex) {}
  get authenticators() {
    return this.knex<DbUser>('users');
  }
}

You could use the generated class in the folloing manner:

db.ts:

import knex from 'knex';

import { DB } from './DbTypes';
import { config } from './config';
import { registerService } from './registerService';

class DBT extends DB {
  transaction<T>(callback: (db: DB) => Promise<T>) {
    return this.knex.transaction((trx) => callback(new DB(trx)));
  }
}

export const db = new DBT(
  knex({
    client: 'mysql2',
    // ...
  })
);

Somewhere in the app:

const user = await db.users.where({ username: input.username }).first();
// user is DbUser | undefined
1.0.37

9 months ago

1.0.36

9 months ago

1.0.33

11 months ago

1.0.32

11 months ago

1.0.35

11 months ago

1.0.34

11 months ago

1.0.31

1 year ago

1.0.29

2 years ago

1.0.30

2 years ago

1.0.26

2 years ago

1.0.28

2 years ago

1.0.27

2 years ago

1.0.25

3 years ago

1.0.19

3 years ago

1.0.22

3 years ago

1.0.21

3 years ago

1.0.20

3 years ago

1.0.24

3 years ago

1.0.23

3 years ago

1.0.18

3 years ago

1.0.17

4 years ago

1.0.16

4 years ago

1.0.15

4 years ago

1.0.14

4 years ago

1.0.11

4 years ago

1.0.13

4 years ago

1.0.12

4 years ago

1.0.10

4 years ago

1.0.9

4 years ago

1.0.8

4 years ago

1.0.7

4 years ago

1.0.6

4 years ago

1.0.5

4 years ago

1.0.4

4 years ago

1.0.3

4 years ago

1.0.2

4 years ago

1.0.1

4 years ago

1.0.0

4 years ago