I'm trying to use Twilio Access Token on Firebase Functions with TypeScript.
export const returnToken = functions.https.onRequest((req, res) => {
const twilioAccessToken = twilio.jwt.AccessToken;
const envconf = functions.config();
const twilioAccountSid = envconf.twilio.sid; //saved them on environment
console.log(twilioAccountSid); //prints out fine
console.log(typeof twilioAccountSid !== "undefined"); //returns true
const twilioApiKey = envconf.twilio.apikey;
console.log(twilioApiKey); //prints fine too
const twilioApiSecret = envconf.twilio.apisecret;
console.log("gonna make a token"); //prints
const token = twilioAccessToken( //here it says TypeError: Cannot set property 'accountSid' of undefined
twilioAccountSid,
twilioApiKey,
twilioApiSecret
)
console.log("gonna make a grant");
const grant = new twilioAccessToken.VideoGrant();
token.addGrant(grant);
grant.room = "someroom";
token.identity = "someid";
res.send(token.toJwt());
})
and I get an error for the twilioAccessToken constructor which says
TypeError: Cannot set property 'accountSid' of undefined
Looking the source ->
function AccessToken(accountSid, keySid, secret, options) {
if (!accountSid) { throw new Error('accountSid is required'); }
if (!keySid) { throw new Error('keySid is required'); }
if (!secret) { throw new Error('secret is required'); }
options = options || {};
this.accountSid = accountSid;
AccessToken is a constructor, but your calling it like a regular function..
const token = twilioAccessToken(
You need to use new
const token = new twilioAccessToken(
Normal Javascript notation is if a function starts with a capital letter, it's a hint that it's a constructor. To keep with this standard I would say you want to also rename twilioAccessToken to TwilioAccessToken..
Related
I'm trying to query parameters localhost:8888?title=associate&name=John and I have written the code below, but editor shows errors in if-else statement. Is the whole concept incorrect? The idea is that if there's no parameters, it would use the default values "who" and "department".
const handleRequest = (request) => {
const url = new URL(request.url);
const params = url.searchParams;
let who = "employee";
let department = "admin";
if (params.has("title") || params.has("name")) {
return new Response(`Please address your request to ${params.get("title")} called ${params.get("name")}.`);
} else {
return new Response(`Please address your request to ${who} in the ${department}.`);
}
};
URLSearchParams object provides lots of methods (like get(param), has(param)) to access the query string parameters.
const url = new URL(
'http://example.com/path/index.html?message=hello&who=world'
);
url.searchParams.get('message'); // => 'hello'
url.searchParams.get('missing'); // => null
//So you can simply use
let messageParam = url.searchParams.get("message") || "default value";
You can read more about it here
https://dmitripavlutin.com/parse-url-javascript/#31-parsing-query-string
const db = require('quick.db')
const Discord = require('discord.js')
module.exports = (client) => {
client.on('guildMemberAdd', (member, message) => {
let welcomechannel = db.get(`welcome_${message.guild.id}`)
let welcomemsg = db.get(`Welcomemsg_${message.guild.id}`)
if(welcomechannel = null || undefined) return
if(welcomemsg = null || undefined) welcomemsg = `Hey <#${member.id}>! Make sure to read the rules and have a great time!`
let embed = new Discord.MessageEmbed()
.setColor('GOLD')
.setDescription(welcomemsg)
welcomechannel.send(embed)
})
}
The guildMemberAdd event is emitted only with a member parameter.
You have to access the guild property from the member object.
let welcomechannel = db.get(`welcome_${member.guild.id}`)
let welcomemsg = db.get(`Welcomemsg_${member.guild.id}`)
There are a couple more issues in your code. = is the assignment operator in JS. You want to use == or === (strict equality) for comparisons. And your condition to check for multiple values isn't right.
if (!welcomechannel === null || welcomechannel === undefined) {
return
}
Or better
if(!welcomechannel) {
return
}
Similarly, you can fix the welcomemsg condition with the following.
if(!welcomemsg) {
welcomemsg = `Hey <#${member.id}>! Make sure to read the rules and have a great time!`
}
Or better
const DEFAULT_MESSAGE = `Hey <#${member.id}>! Make sure to read the rules and have a great time!`
const welcomemsg = db.get(`Welcomemsg_${guildId}`) || DEFAULT_MESSAGE
Here's the fixed code.
client.on('guildMemberAdd', (member) => {
const { id: guildId } = member.guild
const welcomechannel = db.get(`welcome_${guildId}`)
const DEFAULT_MESSAGE = `Hey <#${member.id}>! Make sure to read the rules and have a great time!`
const welcomemsg = db.get(`Welcomemsg_${guildId}`) || DEFAULT_MESSAGE
if (!welcomechannel) {
return
}
// rest of the code
})
I have a Lambda function which runs in Node.js 4.3. The input parameter of the function is a String, which is being sent from an AWS Lex bot.
I want to get an item from a DynamoDB table. In this item I have a Map-type attribute, which contains a String key and String value. I want to get a value from that map using the key String I got as a parameter at the start of the function.
The problem is that when I log the map to the console, all I see there is {}.
This is my code:
var AWS = require('aws-sdk');
AWS.config.region = 'us-east-1';
var dynamodb = new AWS.DynamoDB();
const sessionAttributes = intentRequest.sessionAttributes;
const slots = intentRequest.currentIntent.slots;
const name = slots.names;
var id = null;
if (name == "a") {
id = "00";
} else if (name == "b") {
id = "01";
}
var params = {
TableName: 'names',
Key: {
'id' : {S: 'test-id'}
}
};
var names = {};
dynamodb.getItem(params, function(err, data) {
if (err) {
console.log(err); // an error occurred
} else {
names = data.Item.names.M;
}
});
console.log(names);
var content = names[id];
callback(close(sessionAttributes, 'Fulfilled',
{'contentType': 'PlainText', 'content': content}));
As you can see, there is a console.log line at the end of the code. This line logs just {}. The final message's content is undefined.
What can I do to fix this?
dynamodb.getItem() is executing asynchronously, it has a callback function for this very reason.
console.log(names) is executing before any value is returned in the call to dynamodb.
Add a console.log() inside the getItem function and you will see that this is true.
Google "asynchronous javascript" and you'll find some good pointers.
I am getting an undefined when trying to use the search bar in my app. The components compile fine in webpack. I am not sure if I am having an es6 syntax issue or am missing something inside the operation of the components.
const axios = require('axios');
const OPEN_WEATHER_MAP_URL =
'http://samples.openweathermap.org/data/2.5/weather?appid=5d0a2ef2cca550311d7015dc03763d54&units=imperial';
module.exports = {
getTemp(location) {
var encodedLocation = encodedURIComponent(location);
var requestUrl = `${OPEN.WEATHER_MAP_URL}&q=${encodedLocation}`;
axios.get(requestUrl).then((res) => {
if (res.data.cod && res.data.message) {
throw new Error(res.data.message)
} else {
return res.data.main.temp;
}
((res) => {
throw new Error(res.data.message);
})
})
}
};
I get the error when I trigger the search in the search bar I get the undefined at var encodedLocation = encodedURIComponent(location);
I have tried using let and const instead of var, but this also did not help
Fix a small typo:
Change
var encodedLocation = encodedURIComponent(location);
to
var encodedLocation = encodeURIComponent(location);
I am using nodejs when using destructuring assignment on array process.argv I get error Cannot read property 'next' of undefined.
How to fix this issue? Why is that?
Notes: I am using node v6.9.1
let fileIn, fileOut;
let getNodeArguments = () => {
// this is ok
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
// this is ok
var hasFileInOutArgs = process.argv.length === 4;
if (!hasFileInOutArgs) {
throw ('arguments for file-in and file-out must be provided');
}
// issue
var [, , argUrlIn, argUrlOut] = process.argv; // error exception here <<<
fileIn = argUrlIn;
fileOut = argUrlOut;
};
getNodeArguments();
More infos:
https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Operators/Destructuring_assignment#Nested_object_and_array_destructuring