Google calendar API delay in sending calendar invites - javascript

I have a JS application using the google calendar api, the event is created with the event link but calendar invites usually takes time to be sent to my calendar as the primary owner and sometimes i do not get it. Below is the code snippet, kindly help check it out.
addEvent = async (interview_schedule: any): Promise<any> => {
const calendar = google.calendar({ version: 'v3' });
const event: any = {
summary: interview_schedule.interview.title || 'N/A',
description: interview_schedule.interview.description || 'N/A',
anyoneCanAddSelf: false,
start: {
dateTime: new Date(
`${interview_schedule.date} ${interview_schedule.start_time}`,
),
timeZone: 'Africa/Lagos',
},
end: {
dateTime: new Date(
`${interview_schedule.date} ${interview_schedule.end_time}`,
),
timeZone: 'Africa/Lagos',
},
attendees: interview_schedule.attendees,
reminders: {
useDefault: false,
overrides: [
{ method: 'email', minutes: 60 },
{ method: 'popup', minutes: 10 },
],
},
conferenceData: {
createRequest: {
requestId: interview_schedule.id,
conferenceSolutionKey: 'hangoutsMeet',
},
},
};
try {
const res = await calendar.events.insert({
calendarId: 'primary',
auth: this.client,
sendUpdates: 'all',
conferenceDataVersion: 1,
requestBody: event,
});
console.log('done creating event ', res)
return res.data;
} catch (err) {
console.error(err);
}
};
I have tried searching for sulutions yet no results

Related

NestJS/typeORM Vanilla - Cannot query across many-to-many for property

I'm using NestJS in the vanillaJS way (because I can't write typescript) and I have a many-to-many relation from user to bubble.
I want to write a updateUser-Route in which I also want to be able to update the bubble-affiliation.
But when I do so like this:
user.controller.js:
#Patch(':id')
#Bind(Param('id'), Body())
async updateUser(id, body) {
if (Object.keys(body).length !== 0) {
return await this.userService.updateUser(id, body);
}
throw new BadRequestException('Missing Body');
}
user.service.js:
async updateUser(id, user) {
return await this.userRepository.update(id, user);
}
I get this error:
Cannot query across many-to-many for property bubble
This is my user.entity.js:
var EntitySchema = require('typeorm').EntitySchema;
var User = require('./user.model').User;
var Bubble = require('../bubble/bubble.model').Bubble;
module.exports = new EntitySchema({
name: 'User',
target: User,
columns: {
id: {
primary: true,
type: 'int',
},
handle: {
type: 'varchar',
},
lastCheck: {
type: 'datetime',
default: () => 'NOW()',
},
rating: {
type: 'int',
},
},
relations: {
bubble: {
type: 'many-to-many',
target: 'Bubble',
joinTable: true,
cascade: true,
},
},
});
in postman I try to call it like this:
{
"rating": 10,
"bubble": [{
"id": "1234"
}]
}
if I leave bubble out it works and rating gets updated. with bubble I get the error described above

Embed keeps adding the same fields. Discord.js

I have some commands like user-info in a command handler, here is my code
const Discord = require("discord.js");
const Uembed = new Discord.MessageEmbed();
const randomcolor = Math.floor(Math.random() * 16777214) + 1;
const moment = require("./IGNORE/moment.min.js");
module.exports = {
name: "user-info",
description: "Shows info about a user.",
execute(message, args) {
if (message.deletable) message.delete();
Uembed.setTitle(`${message.author.tag}'s information. `);
Uembed.setColor(randomcolor);
Uembed.setAuthor(message.author.tag, message.author.displayAvatarURL());
Uembed.setThumbnail(message.author.avatarURL());
Uembed.setFooter(
`Requested by : ${message.author.tag}`,
message.author.displayAvatarURL()
);
Uembed.addFields(
{ name: `Username:`, value: `${message.author.username}`, inline: true },
{ name: `Tag:`, value: `${message.author.discriminator}`, inline: true },
{ name: `ID:`, value: `${message.author.id}` },
{ name: `Last message:`, value: `${message.author.lastMessage + 1}` },
{
name: `Joined this server:`,
value: `${moment(message.member.joinedAt).format(
"MMMM Do YYYY, h:mm:ss a"
)}`,
},
{
name: `Account created:`,
value: `${moment(message.author.createdAt).format(
"MMMM Do YYYY, h:mm:ss a"
)}`,
}
);
message.channel.send(Uembed).then((m) => m.delete({ timeout: 60000 }));
},
};
I already tried to put it out of the execute function, but it didn't work either.
Found it! You just need to put this code after the Message.send().
Uembed.fields = [];
It sets the embed fields to an empty array, so it kind of resets the embed fields.

Unable to update record in MongoDB using findOneAndUpdate

I am using Mongoose to update an Announcement record, with the following definition:
const { DateTime } = require('luxon');
const Schema = new mongoose.Schema({
title: String,
description: String,
date: {
type: Date,
set: (dt) => dt.toJSDate(),
get: (d) => DateTime.fromJSDate(d),
},
club: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Club',
},
});
I am performing the update operation in this function
exports.update = async (id, params) => {
console.log(params)
await Announcement.findOneAndUpdate({ _id: id }, params, {
upsert: true,
useFindAndModify: false,
});
return "exports.get(id)";
};
However, I get an error when running Announcement.findOneAndUpdate:
$set' is empty. You must specify a field like so: {$set: {<field>: ...}}
This is what the params look like:
{
title: 'Name!',
description: 'Description!',
date: DateTime {
ts: 1601524800000,
_zone: LocalZone {},
loc: Locale {
locale: 'en-US',
numberingSystem: null,
outputCalendar: null,
intl: 'en-US',
weekdaysCache: [Object],
monthsCache: [Object],
meridiemCache: null,
eraCache: {},
specifiedLocale: null,
fastNumbersCached: null
},
invalid: null,
weekData: null,
c: {
year: 2020,
month: 10,
day: 1,
hour: 0,
minute: 0,
second: 0,
millisecond: 0
},
o: -240,
isLuxonDateTime: true
},
club: '99cb91bdc3464f14678934ca'
}
I know that all the ObjectId's are valid because I have tested them from Mongo shell. However, I can't figure out why I am not able to run findOneAndUpdate on an Announcement record.

Dynamically push, pull, and set on mongoose schema update

I am trying to setup my patch api so that I can create a dynamic query to push, pull, and set data in my mongoose schema. I have plenty of values that I would change using set, but I also have an array of objects which would require me to call push when I need to insert and pull when I need to remove an item. I'm trying to find the best way to combine this into a dynamic structure.
Schema:
const StepSchema = new Schema({
position: {
type: Number,
required: true
},
name: {
type: String,
required: true
},
due_date: {
type: Date
},
status: [{
label: {
type: String,
enum: ['Inactive', 'In Progress', 'Flagged', 'Complete'],
default: 'Inactive'
},
user: {
type: Schema.Types.ObjectId,
ref: 'users',
},
date: {
type: Date
}
}],
comments: [{
user: {
type: Schema.Types.ObjectId,
ref: 'users',
required: true
},
body: {
type: String,
required: true
},
date: {
type: Date,
required: true
},
}],
});
Api:
router.patch('/',
async (req, res) => {
let setQuery = req.body;
let pushQuery = {};
let pullQuery = {};
//remove id from set query
delete setQuery.id;
//if there is a comment
if(req.body.comment){
pushQuery.comments = req.body.comment
}
//if I need to remove a comment
if(req.body.remove_comment){
pullQuery.comments = {_id: req.body.remove_comment.id}
}
//Push new status into array
if(req.body.status) {
pushQuery.status = {
label: req.body.status,
user: req.user._id,
date: new Date()
};
delete setQuery.status;
}
//update step
await Step.findByIdAndUpdate(req.body.id, {$set: setQuery, $push: pushQuery, $pull: pushQuery})
.then(step => {
if(!step){
errors.noflow = "There was a problem updating the step";
return res.status(400).json(errors);
}
res.json(step)
})
.catch(err => {
console.log(err);
res.status(404).json(err);
});
});
I've been getting the following error when trying to push a new status into my document:
operationTime: Timestamp { bsontype: 'Timestamp', low: 1, high_:
1560978288 }, ok: 0, errmsg: 'Updating the path \'status\' would
create a conflict at \'status\'', code: 40, codeName:
'ConflictingUpdateOperators', '$clusterTime': { clusterTime:
Timestamp { bsontype: 'Timestamp', low: 1, high_: 1560978288 },
signature: { hash: [Object], keyId: [Object] } },
Oh, you're doing that $set and $push on a status. Your pushQuery is trying to have status be an array on the document, and your setQuery wants to set it to whatever it was on the actual body (I'm guessing the same object.
A quickfix would be to remove it from the set object:
delete setQuery.status
A reasonable and stable way to do this would be to actually only take the things from req.body which you really want for each of the stages. Example:
const { position, name, dueDate, status, comment, remove_comment } = req.body;
const setQuery = { position, name, dueDate };
const pushQuery = { status, comments: comment };
// ...
That way your queries are not conflicting in any way.

Algolia generate Invalid Secured API-Keys

So I'm trying to generate some secured API-Keys but it seems that they aren't generated right, I've followed the API docs without any luck.
This is what I'm doing
var algoliasearch = require('algoliasearch');
var admin_client = algoliasearch('APP', 'ADMIN_KEY');
var search_client = algoliasearch('APP', 'ONLY_SEARCH_KEY');
var admin_index = admin_client.initIndex('INDEX');
var search_index = search_client.initIndex('INDEX');
admin_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
null { hits:
[ { firstname: 'David',
lastname: 'De Anda',
_tags: [Object],
objectID: '2',
_highlightResult: [Object] } ],
nbHits: 1,
page: 0,
nbPages: 1,
hitsPerPage: 20,
processingTimeMS: 1,
query: 'dav',
params: 'query=dav' }
//-------------------------------------------------
search_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
null { hits:
[ { firstname: 'David',
lastname: 'De Anda',
_tags: [Object],
objectID: '2',
_highlightResult: [Object] } ],
nbHits: 1,
page: 0,
nbPages: 1,
hitsPerPage: 20,
processingTimeMS: 1,
query: 'dav',
params: 'query=dav' }
//-------------------------------------------------
Everything seems to work until now
But now I want to generate some Secured API-Keys
var valid_until = Math.floor(Date.now() / 1000) + 3600
var from_admin_api_key = admin_client.generateSecuredApiKey('from_admin', {validUntil: valid_until});
var from_search_api_key = search_client.generateSecuredApiKey('from_search', {validUntil: valid_until});
var sub_admin_client = algoliasearch('APP', from_admin_api_key);
var sub_search_client = algoliasearch('APP', from_search_api_key);
var sub_admin_index = sub_admin_client.initIndex('INDEX');
var sub_search_index = sub_search_client.initIndex('INDEX');
sub_admin_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
{ Error
at success (/app/node_modules/algoliasearch/src/AlgoliaSearchCore.js:334:32)
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
name: 'AlgoliaSearchError',
message: 'Invalid Application-ID or API key',
debugData:
[ { currentHost: 'https://ge24e6css9-dsn.algolia.net',
headers: [Object],
content: '{"params":"query=dav"}',
contentLength: 22,
method: 'POST',
timeouts: [Object],
url: '/1/indexes/INDEX/query',
startTime: 2017-01-13T17:46:42.519Z,
endTime: 2017-01-13T17:46:44.038Z,
duration: 1519,
statusCode: 403 } ],
statusCode: 403 } undefined
//-------------------------------------------------
sub_search_index.search('dav', (err, content) => { console.log(err, content) });
//------------------CONSOLE-------------------------------
{ Error
at success (/app/node_modules/algoliasearch/src/AlgoliaSearchCore.js:334:32)
at process._tickDomainCallback (internal/process/next_tick.js:129:7)
name: 'AlgoliaSearchError',
message: 'Invalid Application-ID or API key',
debugData:
[ { currentHost: 'https://ge24e6css9-dsn.algolia.net',
headers: [Object],
content: '{"params":"query=dav"}',
contentLength: 22,
method: 'POST',
timeouts: [Object],
url: '/1/indexes/INDEX/query',
startTime: 2017-01-13T17:46:42.519Z,
endTime: 2017-01-13T17:46:44.038Z,
duration: 1519,
statusCode: 403 } ],
statusCode: 403 } undefined
//-------------------------------------------------
I misunderstood the generateSecuredApiKey first parameter that actually was the origin API Key.
So the right code will be
var from_admin_api_key = admin_client.generateSecuredApiKey('ADMIN_KEY', {validUntil: valid_until});
var from_search_api_key = search_client.generateSecuredApiKey('ONLY_SEARCH_KEY', {validUntil: valid_until});
And of course the generated key form the ADMIN_KEY won't work.

Categories