我在网上搜索了有关如何将 Bookshelfjs 与 Typescript 一起使用的示例,但没有任何文章或博客文章可以提供帮助。我确实在 github 上找到了作为 DefinatelyTyped test file 的一部分分发的测试,这是一个很好的起点。此外,您很可能希望将每个模型存储在自己的文件中,这需要 Bookshelfjs 注册表插件。 This article 解释了原因,但在常规 javascript 的上下文中。
假设您已经正确安装了 knexjs 和 bookshelfjs 的类型。以您的代码为灵感,进一步阅读:
您可能有一个名为“Config.ts”的文件,其中包含所有数据库详细信息:
import * as Knex from 'knex';
import * as Bookshelf from 'bookshelf';
export class Config {
private static _knex:Knex = Knex({
client: 'mysql',
connection: {
host : '127.0.0.1',
user : 'your_database_user',
password : 'your_database_password',
database : 'myapp_test',
charset : 'utf8'
}
});
private static bookshelf:Bookshelf = Bookshelf(Config.knex);
public static bookshelf(): Bookshelf {
Config.bookshelf.plugin('registry');
return Config._bookshelf;
}
}
您可能有一个名为“Blog.ts”的文件来保存博客模型(另一个名为“Post.ts”的文件来保存帖子模型):
import {Config} from './Config';
import {Post} from './Post';
export class Blog extends Config.bookshelf.Model<Blog>
{
get tableName() { return 'books'; }
// strongly typed model properties linked to columns in table
public get BlogId(): number {return this.get('id');}
public set BlogId(value: number) {this.set({id: value})}
public get Name(): string {return this.get('name');}
public set Name(value: string) {this.set({name: value});}
posts(): Bookshelf.Collection<Post> {
return this.hasMany(Post);
}
}
module.exports = Server.bookshelf.model('Blog', Blog);
在您的“App.ts”文件中,您可以像这样运行您的代码:
import {Config} from './Config';
import {Blog} from './Blog';
var blog = new Blog();
blog.set({ Name : "My new blog", BlogId : 1 });
.save();
我没有在这里测试代码,所以我可能有一些小错别字,但你明白了。请注意,我对类属性使用了标题大小写,但我对数据库字段使用了蛇形大小写。为了使 Bookshelf 开箱即用,必须遵守某些命名约定,例如每个表的 Id 字段被称为“id”,并且关系的外键具有表名的单数版本(例如,对于 users 表,表中的 Id 将是 'id' 但登录表中的外键是 'user_id')。
无论如何,要想弄清楚如何将 Bookshelfjs 与 TypeScript 思想结合使用(鉴于缺乏关于该主题的文档),最好的方法是结合 DefinatelyTyped typedef bookshelf.d 查看 Bookshelfjs 文档。 ts 文件。