Has anyone received this error when inserting a calendar event using the Google Calendar API? Related to BodyResponseCallback<Schema$Event> ts(2769) - google-calendar-api

I am coding in Typescript and trying to insert an event but I am getting this error that the body of what I am inserting "is not assignable to parameter of type 'BodyResponseCallback<Schema$Event>'." I have tried a few different things and even also seen tutorials do it this way but I don't think the error should be acceptable unless if it really is some bug in the source code? Does anyone see what may be the issue here? Thanks in advance. Please see the code and error message below.
router.post('/create-event', (req: CustomRequest, res, next) => {
try {
void (async () => {
const { description, startDateTime, endDateTime } = req.body
oAuth2Client.setCredentials({
refresh_token:
(hidden)
})
const calendar = google.calendar('v3')
const response = await calendar.events.insert({
auth: oAuth2Client,
calendarId: 'primary',
requestBody: {
description: description,
colorId: '7',
start: {
dateTime: new Date(startDateTime),
},
end: {
dateTime: new Date(endDateTime),
},
// see req.body available properties that could help with timeagent
},
})
res.send(response)
})()
} catch (error) {
console.log(error)
next(error)
}
})
The "auth: oAuth2Client," is underlined in red and says:
(alias) const oAuth2Client: OAuth2Client
import oAuth2Client
No overload matches this call.
Overload 2 of 6, '(callback: BodyResponseCallback<Schema$Event>): void', gave the following error.
Argument of type '{ auth: OAuth2Client; calendarId: string; requestBody: { description: string; colorId: string; start: { dateTime: Date; }; end: { dateTime: Date; }; }; }' is not assignable to parameter of type 'BodyResponseCallback<Schema$Event>'.
Object literal may only specify known properties, and 'auth' does not exist in type 'BodyResponseCallback<Schema$Event>'.ts(2769)

I solved this by adding { responseType: 'json' } as the second argument to the insert function. It seems like an issue with types in the SDK.

Related

Nuxt3: Error using function inside defineEventHandler() in server/api/ file

I am trying to pass some authentication headers to fetch a third party API , but I am getting the following error when running a /server/api/walmart.js file in Nuxt3:
[nuxt] [request error] this[D].init is not a function at new Sign
(https://nuxt-starter-jzgdht.w.staticblitz.com/blitz.331c80ffab288536319518a60349d00207075dad.js:6:1135208)
at Object.createSign
(https://nuxt-starter-jzgdht.w.staticblitz.com/blitz.331c80ffab288536319518a60349d00207075dad.js:6:808197)
at Scheme.sign (./node_modules/node-rsa/src/schemes/pkcs1.js:152:32)
at RSAKey.module.exports.Key.RSAKey.sign
(./node_modules/node-rsa/src/libs/rsa.js:264:40) at
NodeRSA.module.exports.NodeRSA.sign
(./node_modules/node-rsa/src/NodeRSA.js:318:32) at
generateWalmartHeaders (./.nuxt/dev/index.mjs:446:28) at eval
(./.nuxt/dev/index.mjs:458:14) at eval
(./node_modules/h3/dist/index.mjs:364:14) at Object.eval [as handler]
(./node_modules/h3/dist/index.mjs:564:12) at eval
(./node_modules/h3/dist/index.mjs:475:31) [nuxt] [request error]
this[D].init is not a function at new Sign
(https://nuxt-starter-jzgdht.w.staticblitz.com/blitz.331c80ffab288536319518a60349d00207075dad.js:6:1135208)
at Object.createSign
(https://nuxt-starter-jzgdht.w.staticblitz.com/blitz.331c80ffab288536319518a60349d00207075dad.js:6:808197)
at Scheme.sign (./node_modules/node-rsa/src/schemes/pkcs1.js:152:32)
at RSAKey.module.exports.Key.RSAKey.sign
(./node_modules/node-rsa/src/libs/rsa.js:264:40) at
NodeRSA.module.exports.NodeRSA.sign
(./node_modules/node-rsa/src/NodeRSA.js:318:32) at
generateWalmartHeaders (./.nuxt/dev/index.mjs:446:28) at eval
(./.nuxt/dev/index.mjs:458:14) at eval
(./node_modules/h3/dist/index.mjs:364:14) at Object.eval [as handler]
(./node_modules/h3/dist/index.mjs:564:12) at eval
(./node_modules/h3/dist/index.mjs:475:31)
import NodeRSA from 'node-rsa';
const keyData = {
consumerId: '<consumer id removed for this post>',
privateKey: `-----BEGIN RSA PRIVATE KEY-----
MIIEowIBAAKCAQEAiDffvTlnBcHfDhPjYlJhSk+atPFE6HpFaf4mm/aYBXmOn89A
MMulkkmpu+RGj0SaPrpX/ockoSeMuuEPPd3AQ5uZAnJw9TBnE2/kJrPsHaKyVFGV
hZneksIK/KdP/kpGSuVAkocPdit5zKwliMnc6/GVLpDFvU8K2QPnvYu2Jp8XBDwg
gTu2tzHQkrm0cdCYZklKKqN9NdVLJy+6AL50+vX19nHwDdCY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nciefcjck2f880nId1CDldO/f/xlcGcGYXWanohTlYJSZh752DjNc1pM
qmTw2cITx1MiUylVOr0caROi4XrrELUPGSVDA1FOaegSuVE89XhgmdNkRBh0p7Qt
4zYGWQKBgFGuZgbPl76K3fj5POY5OlPusXdCCqJMHKPug+4e5mG82T1KvLFCj1PQ
Fm0y9PoS3A8SXf+aEeLhRqVrpaU4w5RK8PqeF6IB2hpDrHJ8b+3ERU3J7/KuU8Vw
pmwDIbjWypH4dNJgRMti+RKDb9llup6xP5Q4PQRzvUQdklSCp3D8
-----END RSA PRIVATE KEY-----`,
keyVer: 1,
};
const generateWalmartHeaders = () => {
const { privateKey, consumerId, keyVer } = keyData;
const hashList = {
'WM_CONSUMER.ID': consumerId,
'WM_CONSUMER.INTIMESTAMP': Date.now().toString(),
'WM_SEC.KEY_VERSION': keyVer,
};
const sortedHashString = `${hashList['WM_CONSUMER.ID']}\n${hashList['WM_CONSUMER.INTIMESTAMP']}\n${hashList['WM_SEC.KEY_VERSION']}\n`;
const signer = new NodeRSA(privateKey, 'pkcs1');
const signature = signer.sign(sortedHashString);
const signatureEnc = signature.toString('base64');
return {
'WM_SEC.AUTH_SIGNATURE': signatureEnc,
'WM_CONSUMER.INTIMESTAMP': hashList['WM_CONSUMER.INTIMESTAMP'],
'WM_CONSUMER.ID': hashList['WM_CONSUMER.ID'],
'WM_SEC.KEY_VERSION': hashList['WM_SEC.KEY_VERSION'],
};
};
export default defineEventHandler(() => {
const options = {
method: 'GET',
headers: generateWalmartHeaders(), // <--- the error seems to originate from this
return {
api: 'works',
options: options,
};
});
Am I not using the defineEventHandler() correctly there?
#redshift,
1.The const 'options' in the defineEventHandler() function has not closing tag (unterminated).
Keep in mind we're working in server side here, check your functions within generateWalmartHeaders(). Are they all functioning in the backend ?
Fire this code with hard coded headers , and see if it runs / debug it.
Check Docs - they changed the documentation 20th of June sometime later than u posted this question.
check this example...
export default defineEventHandler((event) => {
return {
api: 'works'
}
})
Check my working example , maybe it will help you get on your way :
const config = useRuntimeConfig()
let environment = process.env.NODE_ENV;
let $endpoint = environment == 'development' ? 'http://dev.endpointisdev/' : 'http://prod.production/';
console.log('ENVIRONMENT =', process.env.NODE_ENV)
console.log('$ENDPOINTS =', $endpoint)
export default defineEventHandler(async(event) => {
const productsRequest = await $fetch(`${$endpoint}` +'somelistrequest', {
method: 'POST',
headers: {
'Authorization': 'Basic ' + btoa(`${config.auth_user}:${config.auth_pw}`),
'guiId': '7552662'
},
body: {
reference : "blablabla", //
productListRequest : {
securityKey : `${config._key}`
}
}
});
return responseObject.list
})
IMPORTANT :
I fire this from my store with something like this ..
Now i've encountered a situation today where deployment to production made this api call fail because it needed to be "camelCase"
let submitOrder = await $fetch("/api/submitOrder", {method: 'POST', body: orderPayload});

Cloud Task Creation : Error: 3 INVALID_ARGUMENT: Request contains an invalid argument

I'm following thist tutorial : https://cloud.google.com/tasks/docs/tutorial-gcf
To create a Task that would call a cloud function.
I've done quite some tries and still get this error:
If I change the body encoding to something else, I get another error about serialisation method.
It's likely not a permission issues, as I got some before and got rid of it.
The object which is pass to the createTask() is the following :
task: {
httpRequest: {
url: "https://europe-west1-project_id.cloudfunctions.net/FunctionName"
httpMethod: "POST"
oidcToken: {
serviceAccountEmail: "cf-targetFunctionSA#project_id.gserviceaccount.com"
}
body: ""
headers: {
Content-Type: "application/json"
}
}
(or with body: base64 encoded json string.)
The code I use is the following :
'use strict';
const common = require('./common');
const {v2beta3} = require('#google-cloud/tasks');
const cloudTasksClient = new v2beta3.CloudTasksClient();
let projectName = common.getProjectName();
let location = "europe-west3";
let queue = "compute-stats-on-mysql";
const parent = cloudTasksClient.queuePath(projectName, location, queue);
async function createTask(url, serviceAccount, data)
{
const dataBuffer = Buffer.from(JSON.stringify(data)).toString('base64');
const task = {
httpRequest: {
httpMethod: 'POST',
url:url,
oidcToken: {
serviceAccountEmail: serviceAccount,
},
headers: {
'Content-Type': 'application/json',
},
body:dataBuffer,
},
};
try
{
// Send create task request.
common.logDebug(`Before creating task`, {parent:parent,task:task, data:data});
const [response] = await cloudTasksClient.createTask({parent, task});
common.logDebug(`Created task ${response.name}`, {parent:parent,task:task, response:response, data:data});
return response;
}
catch (error)
{
// Construct error for Stackdriver Error Reporting
console.error("error while creating tasks",error);
}
}
module.exports = {
createTask : createTask,
cloudTasksClient:cloudTasksClient
};
The lack of details in the error makes me hit a wall blind...
Any suggestions ?
My service account was missing a part...
it was
"cf-"+functionName+"#"+projectName+".gserviceaccount.com";
instead of
"cf-"+functionName+"#"+projectName+".iam.gserviceaccount.com";
I left out the ".iam" during my numerous test to make it work.
For sure there's room for improvement in the error messages.
I had same problem. In your case I think there is not property scheduleTime into task param.
To me, the scheduleTime.seconds was with a wrong value.

Flow property is missing in mixed passed - despite the type annotation

I have the following in my declarations file (included in my [libs]):
export type EtlFieldNoIdxT = {
name: Name,
purpose: Purpose,
}
export type EtlFieldT = {
idx: number,
...EtlFieldNoIdxT
}
And the following in my use of the types:
export const createEtlField = (
etlFields: { [Name]: EtlFieldT },
newField: EtlFieldNoIdxT,
) => {
if (etlFields === {}) {
throw new Error({
message: 'Cannot create a new etlField with an empty etlFields',
});
}
const field: EtlFieldT = {
idx: maxId(etlFields, 'idx') + 1,
...newField,
};
const subject: Name = Object.values(etlFields).find(
(f) => f.purpose === 'subject', // <<< f.purpose "missing in mixed" error
).name; // <<< .name "missing in mixed" error
return newEtlField(field, subject);
};
Despite having annotated the input, can flow not infer the type of what Object.values would thus return?
Thank you in advance for pointing out my misunderstanding.
- E
If you check the declaration for Object.values you'll find that it returns an array of mixed:
static values(object: $NotNullOrVoid): Array<mixed>;
A quick google search came back with
https://davidwalsh.name/flow-object-values
So to solve your issue, you wrap Object.values(...) with any, and then inside your find arg you can type it as EtlFieldT and finally refine your type back to EtlFieldT after find.
const subject: Name = ((Object.values(etlFields): any).find(
(f: EtlFieldT) => f.purpose === 'subject',
): EtlFieldT).name;
Though you should be aware that find has the possibility of returning undefined. So to be sound, you should run the find, and declare subject if the value exists.

Using commit in actions with promises returns 'Getters & Setters'

I'm using Vuex's 'actions' to fetch from my database via an API.
It works well and I have a console.log(jsonResponse) which shows the correct data.
However, when I add commit('updateQuestions', jsonResponse) to the picture, the return values for all of the fields are "Setters & Getters"
store.js:
mutations: {
updateQuestionsInit: (state, payload) => {
state.questions.init = payload
}
},
actions: {
onInit: async ({commit}) => {
try {
let response = await fetch('http://localhost:8080/api/mongo/initialforms')
if (response.ok) {
let jsonResponse = await response.json()
console.log(jsonResponse)
// Omitting the below line means it works.
commit('updateQuestionsInit', jsonResponse)
}
}
catch (error) {
console.log('ERROR', error)
}
}
}
Results
Expected Results
[
{
id: 0,
type: "dropdown",
value: "sku",
}, ...
]
Actual Results
[
{
id: Getter & Setter,
type: Getter & Setter
value: Getter & Setter,
…
}, ...
]
Why does this happen and how would it be rectified?
Are you using Firefox? Others experienced similar issues but for them it seemed to work on chrome. Apparently, Firefox shows "Setters & Getters" in the console but the underlying values are correct.
-> Switch to Chrome and see if the issue remains.
References
Vue Getter & Setter instead of the actual values in backend response
https://discourse.mozilla.org/t/webextension-apis-made-as-getter-setter-lazily-evaluating-to-functions-beware-of-mocking-for-unit-tests/30849

(DynamoDB) ConditionExpression behaves unpredictably with an '=' operator. How could I debug it better?

My objects in Dynamodb look roughly like this:
{
userId: "GEFOeE8EsaWmq4NQ3oh7tbeVkLx1",
url: 'objectURL',
object: {}
}
I have this simple piece of code for deleting an object, when the user that owns the object requests a delete. The user argument here is a parsed JWT, by the way.
export async function deleteObject(user, url) {
let params = {
TableName: OBJECTS_TABLE,
Key: {
url: url,
},
ConditionExpression: `userId = :uid`,
ExpressionAttributeValues: {
":uid": {
S: user.sub
}
}
};
let deleteResult = await dynamoDb.delete(params).promise();
return deleteResult;
}
The problem is that it doesn't work, and I've made sure that the problem stems from the ConditionExpression by changing = to <>. I simply get this:
ConditionalCheckFailedException: The conditional request failed
I'm sure solving the problem wouldn't be difficult, but I barely have any information
Questions:
Why is the condition expression failing? Everything looks alright, and it should work. Right?
How could I debug this issue better?
The await/async is not supported by AWS SDK at the moment. Please refer this similar issue.
The SDK currently relies on CLS to trace the call context. It doesn't
work with async/await functionality right now. You can see the
discussion here.
It should work if you remove the await. Example below:-
let deleteResult = dynamodb.deleteItem(params).promise();
deleteResult.then(function (data) {
console.error("Delete item result :", JSON.stringify(data,
null, 2));
}).catch(function (err) {
console.error("Delete item result error :", JSON.stringify(err,
null, 2));
});
I figured it out. ExpressionAttributeValues can be directed used, without mentioning the datatype. The Javascript SDK does that automatically.
export async function deleteObject(user, url) {
let params = {
TableName: OBJECTS_TABLE,
Key: {
url: url,
},
ConditionExpression: `userId = :uid`,
ExpressionAttributeValues: {
":uid": user.sub
}
};
let deleteResult = await dynamoDb.delete(params).promise();
return deleteResult;
}

Resources