Creating routine using google big query client returns 'callback' is not a function error - google-bigquery

Using google biq query client i am trying to run create routine function but it is failing with callback is not a function error
const { BigQuery } = require('#google-cloud/bigquery')
const projectId = 'bigqueryproject1-279307'
const keyFilename = '../credentials/client_secrets.json'
const bigqueryClient = new BigQuery({ projectId, keyFilename })
const dataset = bigqueryClient.dataset('babynames')
const routine = dataset.routine('analysis_routine')
async function createRoutine () {
const config = {
arguments: [{
name: 'x',
dataType: {
typeKind: 'INT64'
}
}],
definitionBody: 'x * 3',
routineType: 'SCALAR_FUNCTION',
returnType: {
typeKind: 'INT64'
}
}
const [routine1, apiResponse] = await routine.create(config)
console.log('*******apiResponse*****', apiResponse)
console.log('****routine1*********', routine1)
}
createRoutine()

See this issue filed against repository

Related

Converting a docx Node.js buffer into pdf file

I am trying to convert the docx document from my node buffer into a pdf document using pdfmake. The pdf is generating but it has no content inside of it. I really don't know where that problem is coming from. I don't mind not using pdfmake, I'm up for anything that can solve the problem really.
`
exports.Resolution = functions.https.onCall(async (data, context) => {
const file_name = 'Resolution.docx';// this is the file saved in my firebase storage
const templateRef = await admin.storage().bucket()
.file(file_name);
const template_content = (await templateRef.download())[0];
const zip = new PizZip(template_content);
let doc;
try {
doc = new Docxtemplater(zip, { linebreaks: true });
} catch (error) {
// Catch compilation errors (errors caused by the compilation of the template : misplaced tags)
errorHandler(error);
}
doc.setData({
date: data.date,
investorName: data.investorName,
companyName: data.companyName,
regNo: data.regNo,
agreements: data.agreements,
governmentEntity: data.governmentEntity,
directors: data.directors,
equityStake: data.equityStake,
governmentEntityName: data.governmentEntityName,
fccp: data.fccp,
investorDirector:data.investorDirector,
equity: data.equity
});
try {
doc.render();
} catch (error) {
errorHandler(error);
}
const contentBuffer = doc.getZip().generate({ type: "nodebuffer" });
const nameofFile = 'Resolution Approving Transaction ' + data.investorName;
const printer = new PdfPrinter(fontss);
const chunks = [];
const pdfDoc = printer.createPdfKitDocument(contentBuffer);
pdfDoc.on('data', (chunk) => {
chunks.push(chunk);
});
pdfDoc.on('end', async () => {
const result = Buffer.concat(chunks);
function mail (){
const dest = context.auth.token.email;
const mailOptions = {
from: 'MPC <mypocketcounsel#gmail.com>',
to: dest,
cc:data.extraEmail,
subject: 'Resolution Approving Transaction',
text: 'Dear ' + data.name+ ',\n\nPlease find attached your Resolution Approving Transaction.\n\nThank you for using MPC Web. \n\n Best regards,\n\n The MPC Team.',
attachments: [
{
filename: nameofFile+'.docx',
content: contentBuffer
},
{
filename: nameofFile +'.pdf',
contentType: 'application/pdf',
content: result
}
]
};
// returning result
return transporter.sendMail(mailOptions);
}
return mail();
});
pdfDoc.on('error', (err) => {
return functions.logger.log('An error occured!');
});
pdfDoc.end();
});
`
This is the function that generates both the docx file and the pdf for me.

Some contract functions runs on hardhat network While others don't

I Got following error while testing my contract
$ npx hardhat test
NftyplayLicense
buyLicense
done!
1) should buy the license successfully
0 passing (2s)
1 failing
1) NftyplayLicense
buyLicense
should buy the license successfully:
Error: invalid address or ENS name (argument="name", value=undefined, code=INVALID_ARGUMENT, version=contracts/5.7.0)
at Logger.makeError (node_modules/#ethersproject/logger/src.ts/index.ts:269:28)
at Logger.throwError (node_modules/#ethersproject/logger/src.ts/index.ts:281:20)
at Logger.throwArgumentError (node_modules/#ethersproject/logger/src.ts/index.ts:285:21)
at /home/bhavesh/Documents/boilerplate/node_modules/#ethersproject/contracts/src.ts/index.ts:123:16
at step (node_modules/#ethersproject/contracts/lib/index.js:48:23)
at Object.next (node_modules/#ethersproject/contracts/lib/index.js:29:53)
at fulfilled (node_modules/#ethersproject/contracts/lib/index.js:20:58)
at processTicksAndRejections (node:internal/process/task_queues:95:5)
Following is the Test that I have written
const { assert, expect } = require("chai")
const { network, ethers, deployments } = require("hardhat")
const { developmentChains } = require("../helper-hardhat-config")
!developmentChains.includes(network.name)
? describe.skip()
: describe("NftyplayLicense", function () {
let nftyplayLicenseContract, nftyPlayLicense, deployer, player, param
beforeEach(async function () {
const accounts = await ethers.getSigners()
deployer = accounts[0]
player = accounts[1]
await deployments.fixture(["all"])
nftyplayLicenseContract = await ethers.getContract("NftyPlayLicensing")
nftyPlayLicense = nftyplayLicenseContract.connect(deployer)
param = {
name: "NftyPlayLicensing",
category: "1",
durationInDays: "1",
licenseType: "1",
nftAddress: "0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC",
nonce: 735,
price: "1000000000000000000",
r: "0xb07df588e0674bc28050a58a7f2cfd315f7e0aec136d0ebcf89fdcd9fa8aa928",
s: "0x109a8b6ff70709d2fecdba8b385097f2f979738518e4c444d4cf95b7e2c9621b",
signer: "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266",
tokenId: "1",
v: 27,
}
})
describe("buyLicense", function () {
it("should buy the license successfully", async function () {
nftyPlayLicense.whitelist("0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC")
console.log("done!")
nftyPlayLicense = nftyplayLicenseContract.connect(player)
await expect(
nftyPlayLicense.buyLicense(param, "https://uri.com", {
value: ethers.utils.parseEther("1"),
})
).to.emit("NftyPlayLicensing", "LicenseBought")
const result = await nftyPlayLicense.getExecutedOrder(735)
assert.equal(result, true)
})
})
})
Note that
nftyPlayLicense.whitelist("0x3C44CdDdB6a900fa2b585dd299e03d12FA4293BC")
is running fine, not not in case of
nftyPlayLicense.buyLicense(param, "https://uri.com", {
value: ethers.utils.parseEther("1"),
})
I've made order and signature object by metamask and stored it locally and then using that i am calling buyLicense function from contract using that object as params.
this is my contract function:
function buyLicense(OrderTypes.LicenseOrder calldata order, string memory uri) public payable {
require(isOrderExecuted[order.nonce] == false, "Order is already Executed");
require(isCancelled[order.signer][order.nonce] == false, "Listing is Cancelled");
bytes32 orderHash = SignatureVerifier.hashMakerOrder(order, ORDER_TYPE_HASH);
validateMakerOrder(order, orderHash);
uint256 licenseTokenId = mintLicenseToken(msg.sender, uri, order);
isOrderExecuted[order.nonce] = true;
emit LicenseBought(
licenseTokenId,
order.price,
order.category,
order.tokenId,
order.signer,
order.licenseType,
order.nftContract
);
}
But I am unable to run that function

How to wait until all async calls are finished

I've got NestJS application which interact with YoutubeAPI and load videos from it.
One particular method is important and it's loadVideos from below. Method it self has multiple asyncs inside and I need to work with videoIdMap property once everything is finished
private loadVideos(
playListId: string,
channel: Channel,
nextPageToken: string,
stopLoadingOnVideoId: string,
) {
const baseUrl = YoutubeService.VIDEO_URL_SNIPPET_BY_ID + playListId;
const response = this.httpService
.get(nextPageToken ? baseUrl + '&pageToken=' + nextPageToken : baseUrl)
.pipe(map((response) => response.data));
response.subscribe((data) => {
data.items.forEach((item) => {
if (stopLoadingOnVideoId && item.snippet.resourceId.videoId === stopLoadingOnVideoId) {
return;
}
this.prepareVideoEntity(item.snippet, channel).then((partialVideo) =>
this.videoService.create(partialVideo).then((video) => {
this.videoIdMap[video.youtubeId] = video.id;
}),
);
});
if (data.nextPageToken) {
this.loadVideos(
playListId,
channel,
data.nextPageToken,
stopLoadingOnVideoId,
);
}
});
}
Ideal solution for me would be to make loadVideos async somehow so I can later do:
public methodWhichCallLoadVideos(): void {
await loadVideos(playListId, channel, null, stopLoadingOnVideoId)
// My code which have to be executed right after videos are loaded
}
Every solution I tried out end up with this.videoIdMap to be empty object or with compilation issue so any idea is more than welcome.
You could switch to promises instead of Observables, thus turning the method into an async one that recurs as long as data has a nextPageToken:
private async loadVideos(
playListId: string,
channel: Channel,
nextPageToken: string,
stopLoadingOnVideoId: string,
) {
const baseUrl = YoutubeService.VIDEO_URL_SNIPPET_BY_ID + playListId;
const response = await this.httpService
.get(nextPageToken ? url + '&pageToken=' + nextPageToken : url).toPromise();
const { data } = response;
for (const item of data.items) {
if (stopLoadingOnVideoId && item.snippet.resourceId.videoId === stopLoadingOnVideoId) {
continue;
}
const partialVideo = await this.prepareVideoEntity(item.snippet, channel);
const video = await this.videoService.create(partialVideo)
this.videoIdMap[video.youtubeId] = video.id;
}
if (data.nextPageToken) {
await this.loadVideos(
playListId,
channel,
data.nextPageToken,
stopLoadingOnVideoId,
);
}
}
In your caller you can then simply await loadVideos(...):
private async initVideoIdMap(...) {
await this.loadVideos(...);
// this.videoIdMap should be correctly populated at this point
}

How to get data from Promise_ object?

I'm trying to get some data from a Promise_ object, in React Native app, in my AsyncStorage.
This is what I get in the console, in my Promise_ object :
Promise {_40: 0, _65: 0, _55: null, _72: null}
_40: 0
_55: {imageId: "1", imageName: "test.png"}
_65: 1
_72: null
__proto__: Object
So I don't know how to simply get the data in the _55 and show them in my code, I just want to take "1" and "test.png".
And sorry for my bad english. Thanks !
CODE :
This is the code for the set :
export const setBadgePicture = async (badgePictureId, badgePictureName) => await AsyncStorage.multiSet([['imageId', badgePictureId],['imageName', badgePictureName]])
and for the get :
export const getBadgePicture = async () => { await AsyncStorage.multiGet(['imageId', 'imageName']).then((response) => { tableResponse = { 'imageId' : response[0][1], 'imageName' : response[1][1], } }) return tableResponse }
you can do this to wait until your AsyncStorage returns the item.
AsyncStorage.getItem('YOUR_KEY').then((response)=>{
const itemVal = response;
})
AsyncStorage getItem function is an Asynchronous function. That means that if you want to get the return of that "get" function you will have to wait for the response. if you are using AsyncStorage.getItem() function add the reserved word await before the statement and in the function you are calling it put the reserved word async like this way:
async myFunctionWhereImCallingTheGetter () {
var myData = await AsyncStorage.getItem('theitemIamSearching');
}
Try then that:
export const getBadgePicture = async () => {
var response = await AsyncStorage.multiGet(['imageId', 'imageName']);
var tableResponse = { 'imageId' : response[0][1], 'imageName' : response[1][1], } });
return tableResponse;
}
What if you avoid multiGet?
export const getBadgePicture = async () => {
var imageId = await AsyncStorage.getItem('imageId');
var imageName = await AsyncStorage.getItem('imageName');
var tableResponse = { 'imageId' : imageId, 'imageName' : imageName };
return tableResponse;
}

How to unit test API calls with axios() in react-native with Jest

I am developing Sample Application in React-native . I used Jest to use unit testing, i don't have an idea about Jest Api call
I want to need without using Promises:
Here this is my Code:
this is My Function Code:
/**
* #description Action to call nilpick service ,on success increment route as well as mark the location as fulfilled
*/
function nilPick() {
return async (dispatch, getState) => {
const currentState = getState();
const { user, picking } = currentState;
const { currentRouteIndex, pickRoute } = getState().picking.pickRouteInfo;
const { workId } = picking.pickWorkInfo;
const nilPickItem = pickRoute[currentRouteIndex];
const currentItem = getCurrentItem(currentState);
const currentTime = dateFunctions.getCurrentUTC();
const nilpickedItem = [
{
orderId: nilPickItem.fulfillOrdNbr,
lineNbr: nilPickItem.ordLine,
pickUpcNbr: nilPickItem.upc,
pickDisplayTs: currentTime,
pickUom: currentItem.workDetail.uom,
pickedLoc: nilPickItem.location,
locationType: nilPickItem.locType,
locId: nilPickItem.locId,
pickByType: currentItem.workDetail.pickByType,
exceptionPick: false,
gtinPrefRankNbr: 0,
pickUpcTypeCd: 5100
}
];
const { status, statusText } = await pickingService.nilPick(nilpickedItem, user, workId);
if (status === 200 || statusText === 'Created') {
console.info('Item nilpicked');
if (currentRouteIndex < pickRoute.length) {
dispatch(incrementRoute());
} else {
Alert.alert(
'Nilpick Complete',
[
{
text: 'OK',
onPress: () => {
dispatch(endPicking());
}
}
],
{ cancelable: false }
);
console.log('End of pickwalk');
return;
}
} else {
console.info('error in nilpicking item ');
}
};
}
This is my code above method to Converting Like this below sample test Case:
This is sample Test i want to call Api How to implement in Jest
it('Test For nillPic', () => {
const initialState = {
picking: {
pickRouteInfo: {
"fulfillOrdNbr": pickRouteInfo.fulfillOrdNbr,
"orderLine": '1',
"upc": '4155405089',
"location": 'A-1-1',
"availableLocsToPick": '2',
'suggSubPendingPicks?': 'N',
'manualSubPendingPicks?': 'N',
"lineFullfilled": 'false',
"currentRouteIndex": 1,
"pickRoute": ['r1', 'r2', 'r3']
}
}
};
// console.log("state data...", initialState);
const store = mockStore(initialState);
store.dispatch(actions.pickRouteActions.nilPickSuccess());
const expectedAction = [{ type: 'INCREMENT_ROUTE' }];
const localActions = store.getActions();
expect(localActions).toEqual(expectedAction);
});
Finally This is my code Please . Thanks in Advance