我正在使用typescript express节点typeorm创建一个应用程序。我有这个问题,当我使用typeorm通过服务类调用数据库时,我找不到连接默认值。这是我的代码片段:
//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;
}
这是我的ormconfig.json
{
"type":"sqlite",
"entities": ["./models/*.js"],
"database": "./leaveappdb.sql"
}
这是&#34;控制器&#34;通过调用第一个代码段的服务类来响应请求:
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);
}
然后这就是我引导我的应用程序的地方。
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));
答案 0 :(得分:0)
您的配置似乎不错,但是您没有调用或使用ormconfig.json文件创建连接。
例如:
createConnection(./ormconfig.json).then(async connection => {
}).catch(error => console.log("Data Access Error : ", error));
尝试使用或我将为您提供一种使用类对象进行配置以建立数据库连接的方法
在配置文件中:
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,
}
在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));
我认为这可能对您有帮助。
此外,我发现要连接sqlite DB,您正在尝试连接sql文件。请确认一次。
谢谢