Snippets

chromawallet Cities

Created by Riccardo Sibani last modified
class city { key name; population: integer; }

operation insert_city (name, population: integer) {
    create city (name, population);
}

query get_all_cities_id(): list<city> {
    return city @*{};
}

query get_all_cities_info(): list<(name: text, population: integer)> {
    return city @*{}(.name, .population);
}

query get_all_cities_object() {
    return city @* {}(name_of_the_city = .name, number_of_residents = .population);
}
const pcl = require("postchain-client");
const node_api_url = "http://localhost:7740"; // using default postchain node REST API port

// default blockchain identifier used for testing
const blockchainRID = "78967baa4768cbcef11c508326ffb13a956689fcb6dc3ba17f4b895cbb1577a3";

const rest = pcl.restClient.createRestClient(node_api_url, blockchainRID, 5);

const gtx = pcl.gtxClient.createClient(
    rest,
    Buffer.from(blockchainRID, 'hex'),
    []
);

const adminPUB = Buffer.from(
    '031b84c5567b126440995d3ed5aaba0565d71e1834604819ff9c17f5e9d5dd078f',
    'hex'
);
const adminPRIV = Buffer.from(
    '0101010101010101010101010101010101010101010101010101010101010101',
    'hex'
);

function add_city(city, population) {
  const rq = gtx.newTransaction([adminPUB]);
  rq.addOperation('insert_city', city, population);
  rq.sign(adminPRIV, adminPUB);
  return rq.postAndWaitConfirmation();
}


function get_all_cities_id() {
    return gtx.query("get_all_cities_id", { });
}

function get_all_cities_info() {
    return gtx.query("get_all_cities_info", { });
}

function get_all_cities_object() {
    return gtx.query("get_all_cities_object", { });
}

(async() => {
    await add_city("Berlin", 3700000);
    await add_city("Stockholm", 1000000);
    const citiesId = await get_all_cities_id();
    console.log("get_all_cities_id", citiesId);
    
    const citiesInfo = await get_all_cities_info();
    console.log("get_all_cities_info", citiesInfo);

    const citiesObject = await get_all_cities_object();
    console.log("get_all_cities_object", citiesObject);
})();

Comments (0)

HTTPS SSH

You can clone a snippet to your computer for local editing. Learn more.