Kai*_* Bo 5 javascript node.js typescript bookshelf.js knex.js
当我们使用时C#,我们可以使用Code-First方法以强类型方式访问我们的数据库:
public class Blog
{
public int BlogId { get; set; }
public string Name { get; set; }
public virtual List<Post> Posts { get; set; }
}
...
public class Database : DbContext
{
public DbSet<Blog> Blogs { get; set; }
public DbSet<Post> Posts { get; set; }
}
var db = new Database()
var blog = new Blog { Name = "My new blog", BlogId = 1 };
db.Blogs.Add(blog);
db.SaveChanges(); // save object to database
Run Code Online (Sandbox Code Playgroud)
编译器将确保我们只访问现有的属性/方法,并且我们在代码中的每个地方都使用正确的类型.
我怎么能TypeScript和Node.JS?
我找到了用于数据库访问的库Knex.JS和bookshelf库,但我找不到任何关于如何将它们与强类型TypeScript对象和类一起使用的示例.
小智 15
我在网上搜索了如何使用Bookshelfjs和Typescript的例子,没有文章或博客文章可以提供帮助.我确实发现在github上作为DefinatelyTyped 测试文件的一部分分发测试,这是一个很好的起点.此外,您很可能希望将每个模型存储在自己的文件中,这需要Bookshelfjs注册表插件.本文解释了为什么,但在常规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;
}
}
Run Code Online (Sandbox Code Playgroud)
您可能有一个名为"Blog.ts"的文件来保存Blog模型(另一个名为"Post.ts"以保存Post模型):
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);
Run Code Online (Sandbox Code Playgroud)
在您的"App.ts"文件中,您将运行您的代码,如下所示:
import {Config} from './Config';
import {Blog} from './Blog';
var blog = new Blog();
blog.set({ Name : "My new blog", BlogId : 1 });
.save();
Run Code Online (Sandbox Code Playgroud)
我没有在这里测试代码所以我可能会有一些小错字,但你明白了.请注意,我已经为类属性使用了标题大小写,但我在数据库字段中使用了snake case.对于Bookshelf开箱即用,必须遵守某些命名约定,例如每个表的Id字段被称为'id',关系的外键具有单个版本的表名(例如对于users表,表中的Id会是'id'但登录表中的外键是'user_id').
无论如何,最好的方法是找出如何使用TypeScript思想使用Bookshelfjs(鉴于缺少关于该主题的文档),将结合DefinatelyTyped typedef bookshelf.d.ts文件查看Bookshelfjs文档.
您可以在 github 上的DefinelyTyped存储库中找到许多 js 库的类型定义。
您还可以使用此处的tsd工具将这些定义文件添加到您的项目中。
简而言之,您需要在终端中运行这 4 个命令。
$ npm install tsd -g
$ tsd init
$ tsd install knex
$ tsd install bookshelf
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6772 次 |
| 最近记录: |