Mobile的Angular App可以直接写入Cosmos DB吗?

时间:2019-09-30 03:13:44

标签: azure-cosmosdb

我看到Cosmos DB具有星球可扩展性。因此,这意味着我可以在全球范围内创建多个Cosmos DB副本,以更快地响应用户。

但是,我想知道是否还需要Web API才能写入Cosmos DB?如果是这样,我们也需要部署Web API的多个副本。

我的问题是,来自移动设备的Angular App可以直接写入Cosmos DB吗? (两者之间没有API层)

1 个答案:

答案 0 :(得分:0)

是的,您可以使用 @azure/cosmos npm软件包直接写入Cosmosdb。

您可以在angualr服务中使用它,

import * as Cosmos from "@azure/cosmos";

export class CosmosService {

    private static instance: CosmosService;
    private readonly cosmosHost = "<your_db>.documents.azure.com:443/";
    private readonly primaryKey = "<primary_key>";
    private readonly database = "ToDoList";
    private readonly collection = "Items";

    private client: Cosmos.CosmosClient;
    db: Cosmos.Database;
    container: Cosmos.Container;

    public items: Model.Todo[];

    constructor() {
        this.client = new Cosmos.CosmosClient({
            endpoint: `https://${this.cosmosHost}`,
            auth: {
                masterKey: this.primaryKey
            },
            consistencyLevel: "Eventual",
            connectionPolicy: {
                enableEndpointDiscovery: false
            }
        });

        this.db = this.client.database(this.database);
        this.container = this.db.container(this.collection);
    }

    async addItem(todo: Model.Todo) {
        const item = await this.container.items.create(todo)
            .catch(err => console.error(err));
        console.log(item);
    }

    async listCollections(): Promise<Model.Todo[]> {

        const response = await this.container.items
            .readAll<Model.Todo>().fetchAll();
        console.warn(response);
        this.items = response.resources;
        console.log(`${this.items.length} items received`);
        return this.items;
    }

    public static getInstance(): CosmosService {
        if (!CosmosService.instance)
            CosmosService.instance = new CosmosService();
        return CosmosService.instance;
    }
}

这里是带有 Ionic 的示例应用程序,当然您也可以将其与angular一起使用。但我建议您在中间使用Web API