typescript express typeorm createconnection

10,093

Your configuration is seems to be good but you didn't called or used your ormconfig.json file to createConnection.

for Eg:

createConnection(./ormconfig.json).then(async connection => {
}).catch(error => console.log("Data Access Error : ", error));

Try with or i will give you a way to configure with class object to establish a DB connection

In config file:

import "reflect-metadata";
import { ConnectionOptions } from "typeorm";
import { abc } from "../DatabaseEntities/abc";
import { def } from '../DatabaseEntities/def';

export let dbOptions: ConnectionOptions = {
            type: "sqlite",
            name: app,
            database: "./leaveappdb.sqlite3", 
            entities: [abc, def],
            synchronize: true,
} 

In server.ts

import { createConnection, createConnections } from 'typeorm';
import * as appConfig from './Config/config';
createConnection(appConfig.dbOptions).then(async connection => {
    console.log("Connected to DB");
}).catch(error => console.log("TypeORM connection error: ", error));

I think this may help you..

Also, i have found that for connecting sqlite DB you are trying to connect a sql file. Kindly confirm that once too.

Thank you

Share:
10,093
Joseph Izang
Author by

Joseph Izang

Christian & Jesus Lover above all else. .NET Core & C#, Typescript & NodeJS Developer. Enjoys Blazor WASM and React.tsx. Enjoys setting up Linux and Windows Servers. Learning & Growing is Life

Updated on June 04, 2022

Comments

  • Joseph Izang
    Joseph Izang almost 2 years

    I am creating an app with typescript express node typeorm. I am having this issue where when I make a call through a service class to the database using typeorm, I get connection default was not found. Here are my code snippets:

    //dataservice class
    import { Connection, getConnection, EntityManager, Repository, 
    getManager } from "typeorm";
    
    export class LeaveDataService {
    private _db: Repository<Leave>;
    
    constructor() {
        this._db = getManager().getRepository(Leave);
    }
    
    /**
     * applyForLeave
     */
    public applyForLeave(leave: Leave): void {
        if(leave !== null) {
            let entity: Leave  = this._db.create(leave);
            this._db.save(entity);
        }
    }
    
    /**
     * getAllLeaves
     */
    public async getAllLeaves(): Promise<Array<Leave>> {
        let leaves: Promise<Array<Leave>> = this._db.find({
            select: ["leaveDays","casualLeaveDays","id","staff","leaveType","endorsedBy","approvedBy"],
            relations: ["staff", "leaveType"],
            skip: 5,
            take: 15
        });
    
        return leaves;
    }
    

    this is my ormconfig.json

    {
        "type":"sqlite",
        "entities": ["./models/*.js"],
        "database": "./leaveappdb.sql"
    }
    

    and this is the "controller" that responds to requests by calling the service class which is the first snippet:

    import { Request, Response } from "express";
    import { LeaveDataService } from "../services/leaveDataService";
    import { LeaveIndexApiModel } from '../ApiModels/leaveIndexApiModel';
    
    
    
    const dataService: LeaveDataService = new LeaveDataService();
    
    export let index = async (req: Request, res: Response) => {
    let result = await dataService.getAllLeaves();
    let viewresult = new Array<LeaveIndexApiModel>();
    
    result.forEach(leave => {
        let apmodel = 
        new LeaveIndexApiModel(leave.leaveType.name, 
    `${leave.staff.firstname} ${leave.staff.lastname}`, leave.id);
        viewresult.push(apmodel);
    });
    
    
    return res.status(200).send(viewresult);
    }
    

    then this is where I bootstrap my app.

    import express = require('express');
    import bodyParser = require('body-parser');
    import path = require('path');
    import * as home from './controllers/home';
    import { createConnection } from 'typeorm';
    import * as leavectrl from "./controllers/leaveController";
    //create express server
    
    
    //create app db connection.
    createConnection().then(async connection => {
    const app = express();
    console.log("DB online!");
    const approot = './';
    const appport = process.env.Port || 8001;
    //setup express for json parsing even with urlencoding
    app.use(bodyParser.json());
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(express.static(path.join(approot,'dist')));
    
    //serve and respond to routes by api
    app.get('/home', home.home);
    app.get('/login',home.login);
    
    //routes for leave
    app.get('/api/leaves', leavectrl.index);
    //default fall through
    // app.get('*', (req: Request, res: Response)=>{
    //     res.sendFile(approot,'dist/index.html');
    // });
    
    app.listen(appport, ()=> console.log(`api is alive on port 
    ${appport}`));
    
    }).catch(error => console.log("Data Access Error : ", error));
    
    • Jonathan
      Jonathan over 5 years
      what line are you getting the error on? If you are only have one connection (vs. ones for development and staging ...) you can name your one connection in your ormconfig 'default'
    • Jesus Gilberto Valenzuela
      Jesus Gilberto Valenzuela over 5 years
      Well, I don't know very much about express, but if I remember, you can use getConnection().manager.getReposiory method, that should read your connection config file and create what you need. My doubt is in your config file, database should be the database name?
    • Joseph Izang
      Joseph Izang over 5 years
      @jonathan default is given by default if you only have one database configuration
    • Joseph Izang
      Joseph Izang over 5 years
      @Jesus Gilberto database is not supposed to be a path! You r right. So u r right