在芭蕾舞演员中使用客户的最佳实践是什么

问题描述 投票:0回答:1
import ballerina/http;
import booksvc.googlebooks as gb;

service / on new http:Listener(9090) {
    resource function get books() returns gb:Book[]|http:InternalServerError {
        gb:Book[]|error books = gb:loadBooks();
        if books is error {
            return http:INTERNAL_SERVER_ERROR;
        } 
        return books;
    }

    resource function get author(string bookname) returns string|http:InternalServerError {
        string|error name = gb:getAuthor(bookname);
        if name is error {
            return http:INTERNAL_SERVER_ERROR;
        }
        return name;
    }
}

我必须使用 OpenApi 客户端来实现功能

loadbooks
getAuthor
。初始化客户端并在这些函数中使用它的最佳实践是什么?

client ballerina
1个回答
0
投票
import ballerina/http;
import booksvc.googlebooks as gb;

service / on new http:Listener(9090) {
    private final http:Client googleBooks;

    function init() returns error?{
        self.googleBooks = check new("https://www.googleapis.com/books/v1/volumes", {auth: {token: apiKey}});
    }

    resource function get books() returns gb:Book[]|http:InternalServerError {
        gb:Book[]|error books = gb:loadBooks(self.googleBooks);
        if books is error {
            return http:INTERNAL_SERVER_ERROR;
        } 
        return books;
    }

    resource function get author(string bookname) returns string|http:InternalServerError {
        string|error name = gb:getAuthor(bookname, self.googleBooks);
        if name is error {
            return http:INTERNAL_SERVER_ERROR;
        }
        return name;
    }
}

在服务级别将客户端维护为私有最终变量,并在服务 init 函数内对其进行初始化。然后将其作为参数传递给

loadBooks
getAuthor
函数。

© www.soinside.com 2019 - 2024. All rights reserved.