簡體   English   中英

使用Node.JS和TypeScript進行強類型數據庫訪問

[英]Strongly-typed database access with Node.JS and TypeScript

當我們使用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

編譯器將確保我們只訪問現有的屬性/方法,並且我們在代碼中的每個地方都使用正確的類型。

我怎么能用TypeScriptNode.JS做同樣的Node.JS

我找到了Knex.JSbookshelf庫來進行數據庫訪問,但我找不到任何關於如何將它們與強類型TypeScript對象和類一起使用的示例。

我在網上搜索了如何使用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;
    }
}

您可能有一個名為“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);

在您的“App.ts”文件中,您將運行您的代碼,如下所示:

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

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

我沒有在這里測試代碼所以我可能會有一些小錯字,但你明白了。 請注意,我已經為類屬性使用了標題大小寫,但我在數據庫字段中使用了snake case。 對於Bookshelf開箱即用,必須遵守某些命名約定,例如每個表的Id字段被稱為'id',關系的外鍵具有單個版本的表名(例如對於users表,表中的Id會是'id'但登錄表中的外鍵是'user_id')。

無論如何,最好的方法是找出如何使用TypeScript思想使用Bookshelfjs(鑒於缺少關於該主題的文檔),將結合DefinatelyTyped typedef bookshelf.d.ts文件查看Bookshelfjs文檔。

是在尋找目前無法獲得的東西。
但是,實際上可以做到! 你將不得不做一些努力工作!

正如您(可能)所知,TypeScript僅在開發時使用,沒有任何內容進入運行時,因此您要求對數據庫結構進行類型驗證。

您必須創建一個在typescript編譯器之前運行的構建步驟,這個新的構建步驟應該從您的數據庫結構中生成一個d.ts文件。 它應該連接到數據庫,調查它,並輸出描述其結構的接口。

請注意,此結構將根據您使用的數據庫而更改...

另一種解決方案是自己手動創建d.ts文件,一旦數據庫結構發生變化,您還必須在定義文件中反映(手動)。

您可以在github上的DefinitelyTyped存儲庫中找到許多js庫的類型定義。

您還可以使用此處tsd工具將這些定義文件添加到項目中。

簡而言之,您需要在終端中運行這4個命令。

$ npm install tsd -g
$ tsd init
$ tsd install knex
$ tsd install bookshelf

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM