使用Node.JS和TypeScript进行强类型数据库访问 [英] Strongly-typed database access with Node.JS and TypeScript

查看:154
本文介绍了使用Node.JS和TypeScript进行强类型数据库访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用C#时,可以使用Code-First方法以强类型方式访问数据库:

When we use C#, we can access our database in a strongly-typed manner using Code-First approach:

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

编译器将确保我们仅访问现有的属性/方法,并确保在代码中的所有位置使用正确的类型.

The compiler will encure that we only access existing properties/methods and also that we use correct types everywhere in our code.

如何使用TypeScriptNode.JS做同样的事情?

How can I do the same with TypeScript and Node.JS?

我找到了Knex.JSbookshelf库用于数据库访问,但是我找不到任何有关如何将它们与强类型TypeScript对象和类一起使用的示例.

I found Knex.JS and bookshelf libraries for database access, but I cannot find any samples on how to uses them with strongly-typed TypeScript objects and classes.

推荐答案

我在网上搜索了有关如何结合使用Bookhelfjs和Typescript的示例,但没有文章或博客文章可以提供帮助.我确实找到了作为DefinatelyTyped 测试文件在github上,这是一个很好的起点.此外,您很可能希望将每个模型存储在其自己的文件中,这需要使用Bookshelfjs注册表插件. 这篇文章解释了为什么但在常规javascript的情况下.

I searched the web for examples on how to use Bookshelfjs with Typescript and there were no articles or blog posts that could help. I did find tests distributed as part of the DefinatelyTyped test file on github, which were a good starting point. Further, most likely you would want to store each model in its own file, which would require the Bookshelfjs registry plugin. This article explains why but in the context of regular javascript.

将所有内容放在一起,假设您已经正确安装了knexjs和bookshelfjs的类型.以您的代码为灵感,进一步阅读:

Putting it all together, assuming you've installed typings for knexjs and bookshelfjs properly. Using your code as inspiration, read further:

您可能有一个名为"Config.ts"的文件,其中包含您所有的数据库详细信息:

You might have a file called "Config.ts" that has all your database details in it:

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"的文件,来保存Blog模型(以及另一个称为"Post.ts"来保存Post模型):

You might have a filed called "Blog.ts" to hold the Blog model (and another called "Post.ts" to hold the Post model):

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"中文件,您将像这样运行代码:

And in your "App.ts" file you would run your code like so:

import {Config} from './Config';
import {Blog} from './Blog';

var blog = new Blog();
blog.set({ Name : "My new blog", BlogId : 1 }); 
    .save(); 

我还没有在这里测试代码,所以我可能有一些小的错别字,但是您明白了.请注意,我已经为类属性使用了标题大小写,但对于数据库字段却使用了蛇形大小写.为了使书架开箱即用,必须遵守某些命名约定,例如每个表都称为"id"的Id字段,并且关系的外键具有表名的单数形式(例如,对于用户表,表中的ID为"id",但登录表中的外键为"user_id".

I haven't tested the code here so I may have some small typos but you get the idea. Note that I've used title case for class properties, but I've used snake case for the database fields. For Bookshelf to work out of the box certain naming conventions must be adhered to like the Id field for every table being called 'id' and foreign keys for relationships have singular version of table name (e.g. for users table, the Id in the table would be 'id' but the foreign key in the login table would be 'user_id').

无论如何,找出具有TypeScript思想的Bookhelfjs的最佳方法(鉴于有关该主题的文档不足)将是结合使用DefinatelyTyped typedef bookshelf.d来查看Bookshelfjs文档. ts文件.

Anyway, whe best way to figure out how to use Bookshelfjs with TypeScript thought (in light of the lack of documentation on the subject) would be to take a look at the Bookshelfjs documentation in combination with the DefinatelyTyped typedef bookshelf.d.ts file.

这篇关于使用Node.JS和TypeScript进行强类型数据库访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆