简体   繁体   English

打字稿表达打字稿创建连接

[英]typescript express typeorm createconnection

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. 我遇到的问题是,当我使用typeorm通过服务类对数据库进行调用时,找不到默认的连接。 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 这是我的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));

Your configuration is seems to be good but you didn't called or used your ormconfig.json file to createConnection. 您的配置似乎不错,但是您没有调用或使用ormconfig.json文件来创建Connection。

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 在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. 此外,我发现要连接sqlite DB,您正在尝试连接sql文件。 Kindly confirm that once too. 请确认一次。

Thank you 谢谢

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 TypeORM 限制使用 createConnection(...) 创建的连接数 - TypeORM limit number o created connections with createConnection(...) 等压应用程序,TypeORM &amp;&amp; TypeScript &amp;&amp; Express &amp;&amp; Webpack设置问题 - Isomoprhic application, problem with TypeORM && TypeScript && Express && Webpack setup typeorm createConnection 即使在带有 PG 的 MacOS 上使用 Await 也会返回 Pending - typeorm createConnection return Pending even with Await on MacOS with PG TypeORM 关系和表达 - TypeORM relations and express 使用带Java的TypeORM进行快速路由 - Express routing using TypeORM with Javascript 用于 Firebase 的 Cloud Functions 上的 Typeorm + Express - Typeorm + Express on Cloud Function for Firebase 在 heroku 上部署 typeorm/typescript 应用程序 - Deploying typeorm/typescript app on heroku 表达:保留所有DRY创建的猫鼬连接模块(使用新的createConnection方法) - express: keep all DRY creating a mongoose connection module (using the new createConnection method) 无法使用 TypeOrm 并找不到明确的“连接”默认值“ - Cannot use TypeOrm with express “connection ”Default" not found 如何使用express和typeorm正确更新实体 - How to correctly update an entity with express and typeorm
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM