Search code examples
ballerinaballerina-swan-lake

How to create a record array by querying a stream in ballerina?


I have a stream of results coming from the github client as below.

stream<github:Repository, github:Error?> repositories = check githubEp->getRepositories("google", true);

And I have a defined record type named Repository as below.

type Repository record {|
    string repoName;
    int? stargazerCount;
|};

How do I create an array of Repository records by querying the stream?


Solution

  • You can follow two approaches here. You can use either query expressions or query actions. You can use it depending on the use case.

    1. Query Expressions - If your requirement is create a new array by filtering a stream.
    Repository[] repoArray = check from github:Repository repo in repositories
            select {repoName: repo.name, stargazerCount: repo.stargazerCount};
    
    1. Query Actions - If you already have an array defined and you need to add the values coming from stream to that array.
    Repository[] repoArray = [];
    check from github:Repository repo in repositories
        do {
            repoArray.push({
                repoName: repo.name,
                stargazerCount: repo.stargazerCount
            });
        };