I am stuck with Promise { <pending> } in helper function in ejs file - mysql

Below is my helper function
async function getPriorityList(operatorId) {
let result = await Api.getApisDetail(operatorId);
return result;
};
and below is my modal function
static getApisDetail(operatorId) {
return db.query(
`select id, api_name, api_type,(select priority from api_switching where api_switching.api_id=api_master.id and operator_id=${operatorId}) as priority,(select isActive from api_switching where api_switching.api_id=api_master.id and operator_id=${operatorId}) as isActive from api_master where api_type='Recharge' order by api_name asc`
);
}

Related

How to get Email of the user who performed an activity in Google Drive?

I am trying to get data from Drive Activity API. The data needs to have the following 4 arguments:
User Information
Filename
Activity Type (Edit, Delete, Copy)
Timestamp
I used the following code to get the required data:
function listDriveActivity() {
var arr = [];
const request = {
pageSize: 10
};
try {
const response = DriveActivity.Activity.query(request);
const activities = response.activities;
if (!activities || activities.length === 0) {
Logger.log('No activity.');
return;
}
for (const activity of activities) {
// get time information of activity.
var time = getTimeInfo(activity);
// get the action details/information
var action = getActionInfo(activity.primaryActionDetail);
// get the actor's details of activity
var actors = activity.actors.map(getActorInfo);
// get target information of activity.
var targets = activity.targets.map(getTargetInfo);
arr.push(actors,targets,[action],[time]);
}
Logger.log(arr);
} catch (err) {
Logger.log('Failed with an error %s', err.message);
}
}
function getOneOf(object) {
for (const key in object) {
return key;
}
return 'unknown';
}
function getTimeInfo(activity) {
if ('timestamp' in activity) {
return activity.timestamp;
}
if ('timeRange' in activity) {
return activity.timeRange.endTime;
}
return 'unknown';
}
function getActionInfo(actionDetail) {
return getOneOf(actionDetail);
}
function getUserInfo(user) {
if ('knownUser' in user) {
const knownUser = user.knownUser;
const isMe = knownUser.isCurrentUser || false;
return isMe ? 'people/me' : knownUser.personName;
}
return getOneOf(user);
}
function getActorInfo(actor) {
if ('user' in actor) {
return getUserInfo(actor.user);
}
return getOneOf(actor);
}
function getTargetInfo(target) {
if ('driveItem' in target) {
const title = target.driveItem.title || 'unknown';
return 'driveItem:"' + title + '"';
}
if ('drive' in target) {
const title = target.drive.title || 'unknown';
return 'drive:"' + title + '"';
}
if ('fileComment' in target) {
const parent = target.fileComment.parent || {};
const title = parent.title || 'unknown';
return 'fileComment:"' + title + '"';
}
return getOneOf(target) + ':unknown';
}
This is the example output, when there is some activity in the drive by a user:
User Information: people/107464693787053536449
Filename: Timesheet
Activity Type: Edit
Timestamp: 2022-04-05T04:51:41.862Z
Now, I want to get the user email in User information rather than user id. Can you please guide me how should I do it? Is there any method/function that I could follow?
You have to use People API if you want to get more information about the user, including the email address:
personName: The identifier for this user that can be used with the People API to get more information. The format is people/ACCOUNT_ID. See https://developers.google.com/people/.
More specifically, call people.get with personFields set to emailAddresses:
function getEmailAddress(resourceName = "people/ACCOUNT_ID") {
const optionalArgs = {
personFields: "emailAddresses",
fields: "emailAddresses(value)"
}
const contact = People.People.get(resourceName, optionalArgs);
const emailAddress = contact.emailAddresses[0].value;
return emailAddress;
}

ipfs.add() returns Object [AsyncGenerator] {}

I am unable to figure out what mistake i have done in the code
Whenever i am calling api, ipfs.add('hello') returns [object AsyncGenerator]
https://gateway.ipfs.io/ipfs/[object AsyncGenerator]
const addFile = async () => {
const Added = await ipfs.add('hello');
return Added;
}
const fileHash = await addFile();
return fileHash;
You can iterate over the result of .add() like so:
for await (const item of Added) {
console.log('item', item)
}
item { path: 'QmWfVY9y3xjsixTgbd9AorQxH7VtMpzfx2HaWtsoUYecaX',
cid: CID(QmWfVY9y3xjsixTgbd9AorQxH7VtMpzfx2HaWtsoUYecaX), size: 13 }

Json string array to object in Vuex

In my states I have categories. In the categories array every each category have a settings column where I have saved json array string.
My question it is,how can I turn my string to object by filtering the response ?
My response:
[{"id":4,"name":"Vehicles","slug":"vehicles","settings":"[{"edit":true,"searchable":true}]","created_at":"2019-01-26 16:37:36","updated_at":"2019-01-26 16:37:36"},
This is my loading action for the categories:
const loadCategories = async ({ commit }, payload) => {
commit('SET_LOADING', true);
try {
const response = await axios.get(`admin/store/categories?page=${payload.page}`);
const checkErrors = checkResponse(response);
if (checkErrors) {
commit('SET_DIALOG_MESSAGE', checkErrors.message, { root: true });
} else {
commit('SET_STORE_CATEGORIES', response.data);
}
} catch (e) {
commit('SET_DIALOG_MESSAGE', 'errors.generic_error', { root: true });
} finally {
commit('SET_LOADING', false);
}
};
This is my SET_STORE_CATEGORIES:
const SET_STORE_CATEGORIES = (state, payload) => {
state.categories=payload.data;
state.pagination = {
currentPage: payload.current_page,
perPage: payload.per_page,
totalCategories: payload.total,
totalPages: payload.last_page,
};
};
Here I would like to add to modify the value ,to turn the string to object.
Had to add:
let parsed=[];
parsed=response.data.data.map((item)=>{
console.log(item);
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
response.data.data=parsed;
commit('SET_STORE_CATEGORIES', response.data);
You could map your response data as follows by parsing that string to an object :
let parsed=[];
parsed=response.data.map((item)=>{
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
commit('SET_STORE_CATEGORIES', parsed);

waitOnReceipt function doesn't work in solidity, running on SuperBlocks

Running on https://studio.superblocks.com/ trying to make a a fun game in Solidity. the problem happens when I call waitfor receipt inside the "addKity" function. Any ideas why? I suspect it could be because of a technical issue in superblocks but could very well be because of a coding error I have.
It reaches the "heres" alert but doesn't reach alert("4");
Please let me know your thoughts!
waitForReceipt(txHash, function(receipt){
Javascript File
(function (Contract) {
var web3_instance;
var instance;
var accounts;
function init(cb) {
web3_instance = new Web3(
(window.web3 && window.web3.currentProvider) ||
new Web3.providers.HttpProvider(Contract.endpoint));
accounts = web3.eth.accounts;
var contract_interface = web3_instance.eth.contract(Contract.abi);
instance = contract_interface.at(Contract.address);
cb();
}
function waitForReceipt(hash, cb) {
web3.eth.getTransactionReceipt(hash, function (err, receipt) {
if (err) {
error(err);
}
if (receipt !== null) {
// Transaction went through
if (cb) {
cb(receipt);
}
} else {
// Try again in 1 second
window.setTimeout(function () {
waitForReceipt(hash, cb);
}, 1000);
}
});
}
function addKitty(){
// var KittyName = "he"; //$("#kittyName").val();
// var KittyPrice = 5;//parseInt($("#kittyPrice").val());
const transactionObject = {
from: "0x95c2332b26bb22153a689ae619d81a6c59e0a804",
gas: "1000000",
gasPrice: "1000000",
value:"1000"
};
instance.addNewKitty.sendTransaction("sdad",5, transactionObject, (error, result) => {
if(error){
alert(error);
alert("2");
}
else{
alert("heres");
waitForReceipt(txHash, function(receipt){
alert("4");
// if(receipt.status === "0x1"){
// alert("got receipt");
// }
// else{
// alert("5");
// alert("receipt status fail");
// }
});
}
})
}
// function getMessage(cb) {
// instance.message(function (error, result) {
// cb(error, result);
// });
// }
$(document).ready(function () {
init(function () {
// getMessage(function (error, result) {
// if (error) {
// console.error("Could not get article:", error);
// return;
// }
// $('#message').append(result);
// });
$("#addKitty").click(function(){
addKitty();
})
});
});
})(Contracts['CryptoKitties']);
Solidity file
pragma solidity ^0.4.21;
contract CryptoKitties {
address public owner;
struct CKitties{
string name;
uint price;
}
function CryptoKitties() public {
owner = msg.sender;
}
modifier onlyOwner() {
require(msg.sender == owner);
_;
}
mapping (address => uint) kittytoUser;
CKitties[] kitties;
event NewCryptoKitty(address owner, string name, uint price);
modifier cost (uint minCost){
require(msg.value>= minCost && minCost >=0);
_;
}
function addNewKitty(string newName, uint newPrice) public payable cost(5000) {
address sender = msg.sender;
uint place = kitties.push(CKitties(newName,newPrice));
kittytoUser[sender] = place;
emit NewCryptoKitty(sender, newName, newPrice);
}
function kill() public onlyOwner{
selfdestruct(owner);
}
function getName() public view returns (string){
address sender = msg.sender;
uint index = kittytoUser[sender]-1;
return kitties[index].name;
}
function setName(string newName) public{
address sender = msg.sender;
uint index = kittytoUser[sender]-1;
kitties[index].name = newName;
}
function getBalance() public view returns (uint){
return address(this).balance;
}
}
First, the waitForReceipt function is getting called passing an undefined value txHash. In that context, it should be result instead (the value coming from the callback that activated that call, triggered by sendTransaction).
That change will make waitForReceipt call work.
The other problem is that you have the web3 variable named as web3_instance, but you still refer to it as web3.
Considering that, inside waitForReceipt, you are still referencing to it as web3.eth..., while the correct call in that context would be: web3_instance.eth.getTransactionReceipt....
With that fixed, alert("4") will get called as intended.

How to return value with callback function and regular func

I want to get object companies from localStorage if exist and
return it
and go to server and update companies in localStorage
if localStorageCompanies is empty i need to subscribe the one who
called the
function to get the result from the server, hot i do it?
and how i exeute this code:
localStorage.setItem('companies',JSON.stringify(res.result));
After this code:
if(!localStorageCompanies){
return res;
}
getCompanies(): any {
const localStorageCompanies = localStorage.getItem('companies');
this.http.get(environment.apiUmbracoUrl+'home/GetCompanies').subscribe(
res => {
//this.sharedService.turnOnLoader();
if(res.rc == 0){
localStorage.setItem('companies',JSON.stringify(res.result));
if(!localStorageCompanies){
return res;
}
}
});
if(localStorageCompanies){
return {rc:1,result:JSON.stringify(localStorageCompanies)};
}
}