如何为微风实体生成打字稿接口/定义 [英] How to generate typescript interfaces/definitions for breeze entities

查看:65
本文介绍了如何为微风实体生成打字稿接口/定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是SPA的新手,我正以杜兰度和微风来学习它.最近,我将解决方案切换到Typescript,我想知道是否有任何好的解决方案可以基于服务器上的EF模型在TypeScript中生成类型化的微风实体.我唯一发现的是这篇文章 Breeze.js类型的实体,但这是只是一小段代码,甚至不是真正的项目.我想知道有没有更好的解决方案来解决这个问题?

I’m new to SPA and I’m learning it with durandal and breeze. Recently I have switched my solution to Typescript and I’m wondering is there any good solution to generate typed breeze entities in TypeScript basing on EF model on the server. Only thing I have found is this post Breeze.js typed entities but this is only small piece of code and not even a real project. I’m wondering is there any better solution to this issue?

推荐答案

下面是一个页面,您可以将其放在您的网站中以生成打字稿界面定义.该页面获取微风的元数据,然后遍历所有类型,并为每种类型输出一个打字稿接口声明.然后可以将此页面的输出粘贴到任何打字稿文件(* .ts)或打字稿定义文件(* .d.ts)中.如果要为接口命名空间,请将结果括在模块声明中:declare module northwind { ... paste interfaces here... }.

Below is a page you can drop in your site to generate typescript interface definitions. The page fetches the breeze metadata then iterates through all of the types and outputs a typescript interface declaration for each type. The output of this page can then be pasted in any typescript file (*.ts) or typescript definition file (*.d.ts). Enclose the results in a module declaration if you want to namespace the interfaces: declare module northwind { ... paste interfaces here... }.

在使用页面之前,您需要进行一次将实体管理器的控制器URL从"api/northwind"更改为微风控制器的URL.

Before using the page you'll need to make one edit: change the entity manager's controller url from "api/northwind" to whatever your breeze controller's url is.

生成的接口依赖于您可以在此处获取的Knockout.js打字稿定义: https://github.com/borisyankov/DefinitelyTyped/tree/master/knockout/

The generated interfaces have a dependency on the Knockout.js typescript definitions which you can grab here: https://github.com/borisyankov/DefinitelyTyped/tree/master/knockout/

使用 learn.breezejs.com 中的northwind示例,此定义生成器页面的输出将如下所示:

Using the northwind example from learn.breezejs.com, the output of this definitions generator page would be something like this:

export interface Employee extends breeze.Entity {
    FirstName: KnockoutObservable<string>;
    LastName: KnockoutObservable<string>;
}

然后您可以使用微风执行查询并将结果转换为这样的员工数组:

you could then execute a query using breeze and cast the results to an array of employees like this:

var manager = new breeze.EntityManager('api/northwind');

var query = new breeze.EntityQuery()
    .from("Employees");

manager.executeQuery(query).then(data => {
    // ***cast the results to a strongly typed array of Employee***
    var employees = <Employee[]>data.results;
}).fail(e => {
    alert(e);  
});

下面是定义生成器页面-将一个新的html文件添加到名为"definitions.html"的项目中,运行该项目并导航到该页面.

below is the definitions generator page- add a new html file to your project named "definitions.html", run the project and navigate to the page.

<html>
<head>
    <title>Typescript Definition Generator</title>
    <style>
        code {
            white-space: pre;
        }
    </style>
    <script src="//code.jquery.com/jquery-2.1.0.min.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/knockout/knockout-3.0.0.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/q.js/1.0.0/q.min.js"></script>
    <script src="//cdnjs.cloudflare.com/ajax/libs/breezejs/1.4.4/breeze.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function () {
            var entityManager = new breeze.EntityManager('api/northwind');
            entityManager.fetchMetadata()
                .then(function () {
                    var html = '',
                        types = entityManager.metadataStore.getEntityTypes(),
                        type,
                        i,
                        j,
                        property,
                        crlf = String.fromCharCode(13),
                        code = document.createElement('code'),
                        script = document.createElement('script');

                    function getJSType(metadataType) {
                        if (/(Int64)|(Int32)|(Int16)|(Byte)|(Decimal)|(Double)|(Single)|(number)/.test(metadataType))
                            return 'number';
                        else if (/(DateTime)|(DateTimeOffset)|(Time)|(Date)/.test(metadataType))
                            return 'Date';
                        else if (/(Boolean)/i.test(metadataType))
                            return 'boolean';
                        return 'string';
                    }

                    for (i = 0; i < types.length; i++) {
                        // type declaration
                        var type = types[i];
                        html += 'export interface ' + type.shortName;

                        // base type
                        html += ' extends ';
                        if (type.hasOwnProperty('baseEntityType')) {
                            html += type.baseEntityType.shortName;
                        } else {
                            html += 'breeze.Entity';
                        }
                        html += ' {' + crlf;

                        // data properties
                        for (j = 0; j < type.dataProperties.length; j++) {
                            property = type.dataProperties[j];
                            if (type.baseEntityType && type.baseEntityType.dataProperties.filter(function (p) { return p.name === property.name; }).length > 0)
                                continue;
                            html += '    ' + property.name;
                            //if (property.isNullable)
                            //    html += '?';
                            html += ': KnockoutObservable&lt;';
                            html += getJSType(property.dataType.name);
                            html += '&gt;; //' + property.dataType.name + crlf;
                        }

                        // navigation properties
                        for (j = 0; j < type.navigationProperties.length; j++) {
                            property = type.navigationProperties[j];
                            if (type.baseEntityType && type.baseEntityType.navigationProperties.filter(function (p) { return p.name === property.name; }).length > 0)
                                continue;
                            html += '    ' + property.name;
                            //if (property.isNullable)
                            //    html += '?';
                            if (property.isScalar)
                                html += ': KnockoutObservable&lt;';
                            else
                                html += ': KnockoutObservableArray&lt;';
                            html += property.entityType.shortName;
                            html += '&gt;;' + crlf;
                        }

                        html += '}' + crlf + crlf;
                    }

                    code.innerHTML = html;

                    $(code).addClass('prettyprint');

                    document.body.appendChild(code);

                    script.setAttribute('src', '//google-code-prettify.googlecode.com/svn/loader/run_prettify.js');
                    document.body.appendChild(script);
                })
                .fail(function (reason) {
                    alert(reason);
                });
        });
    </script>
</head>
<body>
</body>
</html>

这篇关于如何为微风实体生成打字稿接口/定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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