Webservice in hyperledger composer - hyperledger

I am a beginner with hyperledger composer. I want to use webservice API for request/response json inside JavaScript Transaction. it is possible or not? if you have any examples with this please tell me. Thank in advance!
[
{
"firstname": "string",
"lastname": "string",
"gender": "string"
}
]

You can do that using request-promise module which is availabe to all transaction processor functions via the request global variable. You do not need to add the request or request-promise modules to your package.json file, nor do you need to use the require function to load the modules.
The global request method and all of the convenience methods for the various HTTP methods (request.get, request.post, etc.) are available to transaction processor functions. These methods provide a full set of options for handling request bodies, response bodies, HTTP headers, authentication, cookies, proxies, and TLS/SSL.
Eg:
/**
* Buy a given amount of CONGA stocks.
* #param {org.example.BuyStocks} transaction The transaction.
* #transaction
*/
async function buyStocks(transaction) {
// Look up the current price of the CONGA stock, and parse it into a float.
const priceAsStr = await request.get('http://stocks.org/CONGA');
const price = parseFloat(priceAsStr);
// Get the current participant, and update their stock and balance.
const participant = getCurrentParticipant();
const units = transaction.units;
participant.stockUnits += units;
participant.balance -= price * units;
// Update the current participant in the participant registry.
const participantRegistry = await getParticipantRegistry('org.example.Trader');
await participantRegistry.update(participant);
}
Visit this for reference

Related

Pagination is not working for calls resource in Twilio

Problem: I want API to serve all the calls that were received by any given twilio number. It works just fine initially when the call logs are in 50s but as the number increases the call logs API is becoming very slow as there are too many call logs to fetch and process on our end.
Expected Result: I want to paginate the call logs to fetch only 20 call logs at a time.
I tried using List all calls api
// Download the helper library from https://www.twilio.com/docs/node/install
// Find your Account SID and Auth Token at twilio.com/console
// and set the environment variables. See http://twil.io/secure
const accountSid = process.env.TWILIO_ACCOUNT_SID;
const authToken = process.env.TWILIO_AUTH_TOKEN;
const client = require('twilio')(accountSid, authToken);
client.calls.list({limit: 3})
.then(calls => calls.forEach(c => console.log(c.sid)));
The expected result contain the following:
"calls": [1.., 2.., 3..],
"end": 1,
"first_page_uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls.json?Status=completed&To=%2B123456789&From=%2B987654321&StartTime=2008-01-02&ParentCallSid=CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&EndTime=2009-01-02&PageSize=2&Page=0",
"next_page_uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls.json?Status=completed&To=%2B123456789&From=%2B987654321&StartTime=2008-01-02&ParentCallSid=CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&EndTime=2009-01-02&PageSize=2&Page=1&PageToken=PACAaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa0",
"page": 0,
"page_size": 2,
"previous_page_uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls.json?Status=completed&To=%2B123456789&From=%2B987654321&StartTime=2008-01-02&ParentCallSid=CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&EndTime=2009-01-02&PageSize=2&Page=0",
"start": 0,
"uri": "/2010-04-01/Accounts/ACXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX/Calls.json?Status=completed&To=%2B123456789&From=%2B987654321&StartTime=2008-01-02&ParentCallSid=CAXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX&EndTime=2009-01-02&PageSize=2&Page=0"
But in my case its only returning, even though there are more call logs present
"calls": []
Now since I am not able to get next_page_uri, I am not able to paginate.
How can I get next_page_uri?
If you are using the latest version of the Twilio Node module then you can get all your calls in a couple of ways:
The library automatically handles paging for you. Collections, such as
calls, have list and each methods that page under the hood. With
both list and each, you can specify the number of records you want
to receive (limit) and the maximum size you want each page fetch to
be (pageSize). The library will then handle the task for you.
list eagerly fetches all records and returns them as a list, whereas
each streams records and lazily retrieves pages of records as you
iterate over the collection. You can also page manually using the
page method.
For more information about these methods, view the [auto-generated
library https://www.twilio.com/docs/libraries/reference/twilio-node/).
If you want to use paging anyway, it'd probably recommend the page option:
client.calls.page({ pageSize: 10 }, function pageReceived(page) {
page.instances.forEach(function(call) {
console.log(call);
});
if (page.nextPage) {
page.nextPage().then(pageReceived);
}
})

Does a service worker allow one to simply use long expiration headers on static assets?

Say I have a service worker that populates the cache with the following working code when its activated:
async function install() {
console.debug("SW: Installing ...");
const cache = await caches.open(CACHE_VERSION);
await cache.addAll(CACHE_ASSETS);
console.log("SW: Installed");
}
async function handleInstall(event) {
event.waitUntil(install());
}
self.addEventListener("install", handleInstall);
When performs cache.addAll(), will the browser use its own internal cache, or will it always download the content from the site? This is important, because it one creates a new service worker release, and there are new static assets, the old version maybe be cached by the service worker.
If not then I guess one still has to do named hashed/versioned static assets. Something I was hoping service workers would make none applicable.
cache.addAll()'s behavior is described in the service worker specification, but here's a more concise summary:
For each item in the parameter array, if it's a string and not a Request, construct a new Request using that string as input.
Perform fetch() on each request and get a response.
As long as the response has an ok status, call cache.put() to add the response to the cache, using the request as the key.
To answer your question, the most relevant step is 1., as that determines what kind of Request is passed to fetch(). If you just pass in a string, then there are a lot of defaults that will be used when implicitly constructing the Request. If you want more control over what's fetch()ed, then you should explicitly create a Request yourself and pass that to cache.addAll() instead of passing in strings.
For instance, this is how you'd explicitly set the cache mode on all the requests to 'reload', which always skip the browser's normal HTTP cache and go against the network for a response:
// Define your list of URLs somewhere...
const URLS = ['/one.css', '/two.js', '/three.js', '...'];
// Later...
const requests = URLS.map((url) => new Request(url, {cache: 'reload'}));
await cache.addAll(requests);

Twilio Autopilot Dynamic Say Action with variables from memory

I have a situation where I'm able to store additional details about a customer in memory . But Im unable to access them in the Task Definition .
E.g I'm storing the customer's last purchase amount and last purchase date to be presented if the customer wants to hear it as follows
{
"actions": [
{
"remember": {
"last_Purchase": "17585",
"last_Date":"25-Dec-2020"
}
},
{
"listen":True
}
]
}
They get stored in the memory . However I'm unable to use this in a subsequent task (I'm not using it in the same task as Twilio doesnt supports it ) .
In a subsequent task I want to be able to create a dynamic Say in a task as follows
Dear Customer your last purchase is {memory.last_Purchase} on {memory.last_Date}.
But I guess the syntax is wrong or the way I'm accessing the memory variable is wrong .
Request guidance .
Twilio developer evangelist here.
In JavaScript, you'll need to put a money sign ("$") in front of the brackets surrounding your variable name, so your Say Action would look something like this in JavaScript, like in a Twilio Function:
say = {
"say": `Dear Customer your last purchase is ${memory.last_Purchase} on ${memory.last_Date}.`
}
Additionally, objects saved with the Remember Action are placed at the top-level of the Memory object, so make sure you pull it out with JSON.parse:
let memory = JSON.parse(event.Memory);
The total JS code (say, in a Twilio Function) would look something like
exports.handler = function(context, event, callback) {
let actions = [];
let say = {};
let memory = JSON.parse(event.Memory);
say = {
"say": `Dear Customer your last purchase is ${memory.last_Purchase} on ${memory.last_Date}.`
}
actions.push(say);
let respObj = {
"actions": actions
};
callback(null, respObj);
};
Of course, alternatively, you could use
say = {
"say": "Dear Customer your last purchase is " + memory.last_Purchase + "on
" + memory.last_Date
}

Consolibyte QuickBooks PHP Library - How Do You Pass Parameters To Queued Functions?

I am looking to add a customer to my QB installation using the Consolibyte PHP library. I know that I need to initialize and queue up my requests by using the following:
$Queue = new QuickBooks_WebConnector_Queue('mysql://root:password#localhost/my_database');
$Queue->enqueue(QUICKBOOKS_ADD_CUSTOMER, $id_value);
In the above, I am merely passing in a unique ID when I queue the request ($id_value). Looking at the _quickbooks_customer_add_request() method, I see that there are 9 parameters for the function. How are these parameters set when I call $Queue->enqueue()?
Here's the function definition:
->enqueue($action, $ident = null, $priority = 0, $extra = null, $user = null, $qbxml = null, $replace = true)
From here:
https://github.com/consolibyte/quickbooks-php/blob/master/QuickBooks/WebConnector/Queue.php#L208
Documentation:
* #param string $action An action to be performed within QuickBooks (see the qbXML and QuickBooks SDK documentation, i.e.: "CustomerAdd", "InvoiceAdd", "CustomerMod", etc.)
* #param mixed $ident A unique identifier (if required) for a record being operated on (i.e. if you're doing a "CustomerAdd", you'd probaly put a unique customer ID number here, so you're SOAP handler function knows which customer it is supposed to add)
* #param integer $priority The priority of the update (higher priority actions will be pushed to QuickBooks before lower priority actions)
* #param array $extra If you need to make additional bits of data available to your request/response functions, you can pass an array of extra data here
* #param string $user The username of the QuickBooks Web Connector user this item should be queued for
* #param boolean $replace Whether or not to replace any other currently queued entries with the same action/ident

Apostrophe CMS: Do we have middleware/hook which can set global.data from API?

My requiment is I have an API which will provide user data. In the Apostrophe CMS I need to access the user data from all the layouts (Header, Main, Footer).
I can see gobal.data which is avaiable everywhere in the template. Likewise I need a hook which will call the API and store the response data in the Apostrophe's global.data.
Please let me know if you need further informations.
You could hit that API on every page render:
// index.js of some apostrophe module
// You should `npm install request-promise` first
const request = require('request-promise');
module.exports = {
construct: function(self, options) {
self.on('apostrophe-pages:beforeSend', async function(req) {
const apiInfo = await request('http://some-api.com/something');
req.data.apiInfo = apiInfo;
// now in your templates you can access `data.apiInfo`
});
}
}
But this will hit that API on every single request which will of course make your site slow down. So I would recommend that you cache the information for some period of time.

Resources