1.0.31 • Published 2 months ago

m2tk v1.0.31

Weekly downloads
-
License
MIT
Repository
-
Last release
2 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.31

2 months ago

1.0.29

7 months ago

1.0.30

7 months ago

1.0.26

1 year ago

1.0.28

1 year ago

1.0.27

1 year ago

1.0.25

2 years ago

1.0.19

2 years ago

1.0.22

2 years ago

1.0.21

2 years ago

1.0.20

2 years ago

1.0.24

2 years ago

1.0.23

2 years ago

1.0.18

2 years ago

1.0.17

3 years ago

1.0.16

3 years ago

1.0.15

3 years ago

1.0.14

3 years ago

1.0.11

3 years ago

1.0.13

3 years ago

1.0.12

3 years ago

1.0.10

3 years ago

1.0.9

3 years ago

1.0.8

3 years ago

1.0.7

3 years ago

1.0.6

3 years ago

1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago