How do you query using an index in the Architect Serverless Framework? - serverless

I am trying to query using an index but keep getting this error:
ValidationException: Query condition missed key schema element: trackID
Here is my .arc file
#tables
skytracks
trackID *String
_ttl TTL
#indexes
skytracks
skyTrackType *String
Here is the relevant piece of the http get handler:
const skyTrackType = req.queryStringParameters.skytracktype
const data = await arc.tables()
const trackingData = await data.skytracks.query({
KeyConditionExpression: `skyTrackType = :skyTrackType`,
ExpressionAttributeValues: {
':skyTrackType': skyTrackType
}
})

Architect automatically names the index attribute-index
This needs to be added to the query in the question: IndexName: 'skyTrackType-index'
const trackingData = await data.skytracks.query({
KeyConditionExpression: `skyTrackType = :skyTrackType`,
IndexName: 'skyTrackType-index',
ExpressionAttributeValues: {
':skyTrackType': skyTrackType
}
})

Related

How to look for the specific index of an array once i enter the mortgage id number in twilio function?

This is my code in twilio functions,
exports.handler = function (context, event, callback) {
const got = require('got');
const mortgageInfo = event.mortgageInfo;
const mortgage_number = event.mortgage_number;
got('https://cyan-sparrow-7490.twil.io/assets/data6.json').then (response =>{
const mort = JSON.parse(response.body);
let mortgageData = mort;
//Begin filter code
let val = mortgageInfo;
// I think this line here is my problem
let index = mortgageData.map(function(e) { return e.mortgageid.value; }).indexOf(val);
// I think this line here is my problem
//End filter code
let mortgageSpecificData = mortgageData[index];
callback(null,mortgageSpecificData);
});
===========SAMPLE ASSET ==============
===========SAMPLE ASSET ==============
I think it can be a lot simpler than that. One thing to note is that event.mortgageInfo is going to be a string, but in your data, the mortgageid property is a number. So when you compare, you need to convert first.
Here's a function that I believe will work:
const got = require("got");
exports.handler = function (context, event, callback) {
const mortgageInfo = parseInt(event.mortgageInfo, 10);
got("https://cyan-sparrow-7490.twil.io/assets/data6.json").then(
(response) => {
const mortgageData = JSON.parse(response.body);
const mortgageSpecificData = mortgageData.find(
(mortgage) => mortgage.mortgageid === mortgageInfo
);
callback(null, mortgageSpecificData);
}
);
};
In this case I first change the mortgageInfo into a number by calling parseInt on the event.mortgageInfo. Then, once you fetch the data and parse it, you can find the object with the matching mortgageid using the array's find method. find takes a function that is called with each member of the array and returns when it evaluates to true. In this case, for each member of the array we check whether the mortgageid matches the mortgageInfo we got earlier.
Try this:
const index = mortgageData.findIndex((e) => e.mortgagid === mortgagid)

How to find an array larger than 0, in typeorm?

Hi this is how my Postgres looks like
header is exampleHeader
[{test: 'hi'}] full
null empty
How do I filter andWhere to take out any results that are not full?
I tried the following:
const res = await this.testRepository
.createQueryBuilder('ts')
.where('ts.user_id = :id', { id })
.andWhere('ts.exampleHeader >: num', { num: 0 });
const res = await this.testRepository
.createQueryBuilder('ts')
.where('ts.user_id = :id', { id })
.andWhere(`jsonb_array_length(ts.exampleHeader) >0`);
The above worked for me

How to do multiple updates for the same asset in a transaction

Here I want to do the multiple update commands for the same asset in a single transaction based on conditions.
This is my sample CTO File:
asset SampleAsset identified by id{
o String id
o Integer value
o Integer value2
o Integer value3
}
transaction SampleTransaction {
o Integer value
}
This is my sample JS file:
async function sampleTransaction(tx) {
var value = tx.value;
await updateValue(value);
if(value < MAX){ //MAX=10000
const assetRegistry1 = await getAssetRegistry('org.example.basic.SampleAsset');
var data1 = await assetRegistry.get("1");
data1.value2 = max;
await assetRegistry1.update(data1); //updateNo2
}
else{
const assetRegistry1 = await getAssetRegistry('org.example.basic.SampleAsset');
var data1 = await assetRegistry.get("1");
data1.value3 = value;
await assetRegistry1.update(data1); //UpdateNo2
}
}
async function updateValue(value){
const assetRegistry = await getAssetRegistry('org.example.basic.SampleAsset');
var data = await assetRegistry.get("1");
data.value = value;
await assetRegistry.update(data); //UpdateNo1
}
With the above code, only latest update (UpdateNo2) command is making changes to the asset. what about the first update?
In Hyperledger fabric during proposal simulation any writes made to keys cannot be read back. Hyperledger composer is subject to that same limitation both when it is used with a real fabric implementation as well as when it's used in a simulation mode (for example when using the web connection in composer-playground).
This is the problem you are seeing in your TP function. Every time you perform
let data = await assetRegistry.get("1");
in the same transaction, you are getting the original asset, you don't get a version of the asset that has been updated earlier in the transaction. So what is finally put into the world state when the transaction is committed will be only the last change you made which is why only UpdateNo2 is being seen.
Try something like this (Note I've not tested it)
async function sampleTransaction(tx) {
const assetRegistry = await getAssetRegistry('org.example.basic.SampleAsset');
const data = await assetRegistry1.get("1");
const value = tx.value;
updateValue(data, value);
if(value < MAX){ //MAX=10000
data.value2 = MAX;
}
else{
data.value3 = value;
}
await assetRegistry1.update(data);
}
function updateValue(data, value){
data.value = value;
}
(Note I have left the function structure in just to show the equivalent but updateValue can easily be removed)

Run firebase cloud function when a key is a specific value

const functions = require('firebase-functions');
var IAPVerifier = require('iap_verifier');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
exports.verifyReceipt = functions.database.ref('/Customers/{uid}/updateReceipt')
.onWrite(event => {
const uid = event.params.uid;
var receipt = event.data.val();
(strReceipt).toString('base64');
var client = new IAPVerifier('IAP_secretkey')
client.verifyAutoRenewReceipt(receipt, true,function(valid, msg, data){
console.log(' RECEIPT');
if(valid) {
console.log('VALID RECEIPT');
console.log('msg:' + msg);
var strData = JSON.stringify(data);
console.log('data"' + strData);
const newReceiptRef = admin.database().ref('/Customers/{uid}/');
newReceiptRef.update({'receiptData1': data});
const recVerRef = admin.database().ref('/Customers/{uid}/');
newReceiptRef.update({'updateReceipt': 0});
// update status of payment in your system
}else{
console.log('INVALID RECEIPT');
console.log('msg:' + msg);
var strData = JSON.stringify(data);
console.log('data"' + strData);
}
});
});
This is my node js cloud function. The possible values for 'updateReceipt' are 0 and 1. Is it possible to run the cloud function only when the value is 1?
Thanks.
There is no way to only trigger the function when a specific value is present.
I can think of two options:
Write the nodes to a different branch depending on the updateReceipt value.
Add an if to your code.
The second options is definitely the simplest:
exports.verifyReceipt =
functions.database.ref('/Customers/{uid}/updateReceipt')
.onWrite(event => {
const uid = event.params.uid;
var receipt = event.data.val();
if (receipt.updateReceipt === 0) {
var client = new IAPVerifier('IAP_secretkey')
...
Alternatively, you can keep the updated receipt in a separate branch from the new receipts. That way you can trigger a function separately for just the new receipts.

How to query VSTS Work Items with Wiql

I need to query VSTS work items using Wiql from vsp-node-api package, Please provide any examples if possible.
Refer to following code for details:
import * as vm from 'vso-node-api/WebApi';
import * as wa from 'vso-node-api/WorkItemTrackingApi';
import * as wi from 'vso-node-api/interfaces/WorkItemTrackingInterfaces';
import * as vss from 'vso-node-api/interfaces/Common/VSSInterfaces';
import * as core from 'vso-node-api/interfaces/CoreInterfaces';
var collectionUrl = "https://xxxxxx.visualstudio.com";
let token: string = "PersonalAccessToekn";
let creds = vm.getPersonalAccessTokenHandler(token);
var connection = new vm.WebApi(collectionUrl, creds);
let vstsWI: wa.IWorkItemTrackingApi = connection.getWorkItemTrackingApi();
async function WIQLquery() {
let teamC: core.TeamContext = {project: "", projectId: "", team: "", teamId: "" };
let wiqls: wi.Wiql = { query: "Select [System.Id] From WorkItems Where [System.WorkItemType] = 'Task' And [System.TeamProject] = 'Project'"};
let queryResult: wi.WorkItemQueryResult = await vstsWI.queryByWiql(wiqls, teamC);
queryResult.workItems.forEach(s=>console.log(s.url));
}
WIQLquery();
Here is how I did it, using Javascript instead of Typescript.
Shout out to Eddie Chen for leading me in the right direction.
// file - models/witModel.js
var azdev = require("azure-devops-node-api");
var Model = function(){};
Model.prototype.getWiqlQuery = function(wiqlQuery, teamName){
return new Promise(function(resolve, reject){
const orgUrl = process.env.ADOURI; // ex. https://dev.azure.com/<your org>
const token = process.env.ADOPAT; // Your personal access token
const teamProject = process.env.ADOPROJ;// Team Project
let authHandler = azdev.getPersonalAccessTokenHandler(token);
let connection = new azdev.WebApi(orgUrl, authHandler);
connection.getWorkItemTrackingApi().then(function(witAPI){
var teamContext = {project: teamProject, team: teamName };
witAPI.queryByWiql(wiqlQuery, teamContext).then(function(queryResult){
resolve(queryResult);
}).catch(function(err){reject(err)});
}).catch(function(err){
reject(err);
});
});
};
module.exports = new Model();
And this was how I used it.
// usage - the above code was saved in a module called witModel.js
// feel free to put the module where you need to.
var witModel = require("./models/witModel.js");
// form query and set the value of the teame to query
var query = {query: "your wiql query"};
var team = "team name in Azure DEvops";
// call the promise and handle resolve/reject - then/catch
witModel.getWiqlQueryResuults(query,team).then(function(data){
console.log(data);
}).catch(function(err){
console.log(err)
});

Resources