'How to represent database tables using TypeScript and Knex.js?

I'm writing API using TypeScript and as query builder I use Knex.js.

The problem is - I just can't get any data from database. As I know, I need to create interfaces or something, that is going to represent data structure from database, but it doesn't work. But nothing works, when I trigger endpoint with this function, it seems like infinite pending, no response.

Here is how I was trying to implement this.

import { Knex } from "knex";
import knex from "../src/db/knex";

interface User {
    name: string
}

export const getUserById = async (id: string) => {
    const query: Knex.QueryBuilder = knex<User>('users');
    const data: User[] = await query.select('*');
    console.log("data:", data)
};

Or:

...
interface User {
    name: string
}

export const getUserById = async (id: string): Promise<User> => {
    return await knex.raw('SELECT * FROM users')
};

Also about this users table. I have created it using migration:

import { Knex } from "knex";
export async function up(knex: Knex): Promise<void> {
    return knex.schema.createTable('users', (tableBuilder: Knex.CreateTableBuilder) => {
        tableBuilder.string('name')
    });
}
export async function down(knex: Knex): Promise<void> {
    return knex.schema.dropTable('users');
}

PS. Here is my knex.ts and knexfile.ts if problem could be there, because I have no idea, why it happens:

Knex.ts

import path from "path";
import Knex from "knex";
import dotenv from "dotenv";
import knexConfig from "./knexfile";

dotenv.config({
    path: path.resolve(path.resolve(), "../../../.env")
})

const enviroment = process.env.NODE_ENV || "development"

const knex = Knex(knexConfig[enviroment]);

export default knex;

// If I want to make/run migration/seed I need to use this and don't forget about --esm
// export default knexConfig;

And here is knexfile.ts

import path from "path";
import dotenv from "dotenv";

dotenv.config({
    path: path.resolve(path.resolve(), "../../../.env")
})

interface IKnexConfig {
    [key: string]: object
}

const knexConfig: IKnexConfig = {
    development: {
        client: 'mysql2',
        connection: {
            host: process.env.DATABASE_HOST,
            user: process.env.DATABASE_USERNAME,
            password: process.env.DATABASE_PASSWORD,
            database: process.env.DATABASE_DATABASE,
        },
        migrations: {
            tableName: 'knex_migrations',
            directory: path.resolve() + '/migrations'
        },
        seeds: {
            directory: path.resolve() + '/seeders'
        },
        debug: true
    }
}

export default knexConfig;


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source