You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何扩展Composer Rest Server及查看Hyperledger Composer查询函数

Hey there! Let's break down your two questions about Hyperledger Composer step by step:

1. Viewing Custom Functions with Query Logic

First off, your custom transaction functions (the ones with query logic) are stored in the lib directory of your Hyperledger Composer business network, usually in a file like logic.js. You can directly open this file to access the complete code. I’ve cleaned up and completed your sample function below for clarity:

/**
 * @param {hansung.ac.kr.transaction.selectUserByCertificateName} tx - The transaction to process
 * @transaction
 */
function selectUserByCertificateName(tx) {
    var idList = [];
    // Call the predefined query "selectCertificateByName" with the provided certificate name
    return query("selectCertificateByName", { targetName: tx.certificateName })
        .then(function (certificateList) {
            // Loop through query results to collect all associated owner IDs
            certificateList.forEach(function (certificate) {
                idList.push(certificate.ownerId);
            });
            // Optional: Add follow-up logic here (e.g., return the list or trigger another action)
            console.log("Collected owner IDs:", idList);
            return idList;
        })
        .catch(function (error) {
            // Handle any errors that occur during the query
            throw new Error("Failed to fetch certificates: " + error.message);
        });
}

Key details to note:

  • The @transaction annotation marks this as an executable transaction function that Composer will recognize and deploy.
  • The query() function calls a predefined query (defined in a .qry file in your business network) and passes the required parameters.
  • Promise chaining is critical here: query() returns a Promise, so we use .then() to handle successful results and .catch() to catch errors. Always return the Promise so Composer can properly manage the transaction’s asynchronous flow.
2. Extending the Composer REST Server

The Composer REST Server is built on LoopBack, so you have several flexible ways to extend its functionality:

  • Add custom middleware
    You can inject middleware to handle requests/responses (e.g., logging, custom auth). Create a middleware file like custom-middleware.js:

    module.exports = function (app) {
        // Simple request logging middleware
        app.use(function (req, res, next) {
            console.log(`[${new Date().toISOString()}] ${req.method} ${req.path}`);
            next();
        });
    };
    

    Start the server with your middleware:

    composer-rest-server -c admin@your-business-network -m ./custom-middleware.js
    
  • Expose custom API endpoints
    Use LoopBack’s router to add custom endpoints. Create a boot file at server/boot/custom-api.js:

    module.exports = function (app) {
        const router = app.loopback.Router();
        // Custom GET endpoint to return owner IDs
        router.get('/api/custom/owner-ids', function (req, res) {
            // Add logic here to call Composer queries or transactions
            res.send({ message: "Custom endpoint response", ownerIds: [] });
        });
        app.use(router);
    };
    

    Restart the server, and you’ll be able to access http://localhost:3000/api/custom/owner-ids.

  • Modify server configuration
    Edit the server/config.json file to tweak LoopBack settings like port, CORS rules, or pagination:

    {
        "port": 3001,
        "restApiRoot": "/api",
        "cors": {
            "origin": "*",
            "credentials": true
        }
    }
    
  • Leverage LoopBack extensions
    Since the REST Server is LoopBack-based, you can use LoopBack’s official extensions (e.g., OAuth2 authentication, database integrations). Install the extension via npm, then enable it in server/component-config.json.

内容的提问来源于stack exchange,提问作者a bc

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:55:42