How to catch an err in node.js? - javascript

How can I catch an error in node.js?
Here's my code:
const { Client, Message, MessageEmbed } = require("discord.js")
const translate = require('#iamtraction/google-translate')
module.exports = {
name: "ترجم",
description: `يترجم اللغه فقط أستعمل !translate "الكلمه/الجمله يلي بدك تترجمها"`,
aliases: ['translate'],
run: async (client, message, args) => {
const query = args.join(" ")
const lang = args[0]
if(!query) return message.reply('Please specify a text to translate');
const translated = await translate(query, { to: lang });
message.reply(translated.text);
},
};
It works when I type in chat:
!translate ar hello
But when I type:
!translate "not a real lang" hello
It shutdowns with the error:
Error: The language 'not a real lang' is not supported
I tried .catch, I tried if and else, I tried try

async functions return a value only if no error occurred. If something goes wrong an error is thrown that has to be caught.
You call the async function that errs with the await keyword, so you have to surround that with a try { } catch (e) {} block like this:
try {
const translated = await translate(query, { to: lang });
message.reply(translated.text);
} catch (e) {
message.reply('Translation failed: ' + e.message);
}
Since you take care of another possible error one line above, you could wrap the whole thing into a try-catch block and take care of all kinds of errors in a unified way:
const { Client, Message, MessageEmbed } = require("discord.js")
const translate = require('#iamtraction/google-translate')
module.exports = {
name: "ترجم",
description: `يترجم اللغه فقط أستعمل !translate "الكلمه/الجمله يلي بدك تترجمها"`,
aliases: ['translate'],
run: async (client, message, args) => {
try {
const query = args.join(" ")
const lang = args[0]
if(!query) throw new Error('Please specify a text to translate');
const translated = await translate(query, { to: lang });
message.reply(translated.text);
} catch (e) {
if (message) {
message.reply('Translation failed: ' + e.message);
}
}
},
};
This way you will get a meaningful reply in any case (as long as you have a valid message). For example, maybe args is not an array.

To catch errors in node.js you usually do this:
try {
// your code here
} catch (error){
console.error(error);
//your error response code here
}

Related

how can i store data in json file Continuous for discord js

I want to take the message information from the user and save it in a JSON file and this data is constantly added, but with the following code, this data is constantly replaced.
and I don't replace data I want to add data
this is my code :
const fs = require("fs");
const { Client, Intents } = require("discord.js");
const client = new Client({
intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
const now = new Date();
const obj = {
table: [],
};
let confirm = false;
const { badWords } = require("../badWordList.json");
client.on("message", async (message) => {
if (message.author.bot) return;
for (let i = 0; i < badWords.length; i++) {
if (message.content.toLowerCase().includes(badWords[i].toLowerCase()))
confirm = true;
}
if (confirm) {
obj.table.push({
name: message.author.username,
date: `${now.getFullYear()}/${now.getMonth()}/${now.getDate()}`,
message: message.channel.messages.channel.lastMessage.cleanContent,
});
fs.writeFile("myjsonfile.json", JSON.stringify(obj), function (err) {
if (err) throw err;
console.log("complete");
});
}
});
When using the fs.writeFile() it replaces the content of the file, as written in the docs.
At a first glance, you might want to use fs.write(), see the docs for usage.
But the NodeJS docs says :
It is unsafe to use fs.write() multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream() is recommended.
Since you are in asynchronous mode, you shoud probably define a write stream to the file and then write to it, it gives you something like that :
// -snip-
const whateverJsonFileStream = fs.createWriteStream("myjsonfile.json");
client.on("message", async (message) => {
//-snip-
if (confirm) {
obj.table.push({
name: message.author.username,
date: `${now.getFullYear()}/${now.getMonth()}/${now.getDate()}`,
message: message.channel.messages.channel.lastMessage.cleanContent,
});
whateverJsonFileStream.write(JSON.stringify(obj), function (err) {
if (err) throw err;
console.log("complete");
});
}
});

Why since my switch to discord js 13, the messageCreate Event bug?

I explain my problem: I use a js file external to my commands for my Events and I have the impression that there are some things that do not work correctly in my messageCreate.js which however worked before with Discord .JS in version 12.
For example, when I want to return as soon as the bot sends a message it doesn't work via the messageCreate.js, I have to put it in all of my commands etc.
In my commands I noticed that the arguments do not work whereas before I had no problems. I was able to verify this by putting a
if(args == undefined) return console.log("test")
and the message "test" was displayed in the console as soon as I tried.
I put my code below, hoping you can help me. :)
the part of my index.js that deals with events:
fs.readdir("./Events/", (err, files) => {
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] ${chalk.cyan('Chargement des évènements ...')}`)
if (err) return Debug.logs(err)
files.forEach(async (file) => {
if (file.endsWith(".js")) {
const event = require(`./Events/${file}`)
let eventName = file.split(".")[0]
try {
bot.on(eventName, event.bind(null, bot))
delete require.cache[require.resolve(`./events/${file}`)]
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] ${chalk.green('Event Chargé :')} ${chalk.cyan(file)}`)
} catch (error) {
Debug.logs(error)
}
} else {
return
}
})
})
my messageCreate.js :
const env = process.env
const chalk = require('chalk')
const moment = require('moment')
const Debug = require('../utils/Debug')
const config = require("../config.json")
module.exports = async (bot, message) => {
if(message.channel.type === "DM"){
if(message.author.bot) return;
message.reply("Les commandes en **messages privés** sont actuellement **désactivées** !")
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] [${chalk.yellow(message.author.tag)}] a envoyé ${chalk.green(message.content)} en DM`)
}else{
if (!message.author.bot) {
if (message.content.startsWith(config.prefix)) {
const args = message.content.slice(config.prefix.length).trim().split(/ +/g)
const command = args.shift().toLowerCase()
const cmd = bot.commands.get(command)
if (cmd) {
await cmd.run(bot, message, args)
Debug.logs(`[${chalk.cyan(moment(Date.now()).format('h:mm:ss'))}] [${chalk.yellow(message.author.tag)}] a utilisé ${chalk.green(command)} ${chalk.cyan(args.join(" "))}`)
} else {
return
}
} else {
return
}
} else {
return
}
}
}
and one exemple of command who not work with messageCreate.js :
const Discord = require("discord.js");
module.exports.run = async (bot, message, config, args) => {
message.delete();
if(args == undefined) return console.log("wtf that not work ?")
}
module.exports.help = {
name:"test",
desc:"test commands !",
usage:"test",
group:"autre",
examples:"$test"
}
module.exports.settings = {
permissions:"false",
disabled:"false",
owner:"false"
}
as soon as I run the command with argument or without any argument, in both cases the console receives the message "wtf that not work?"
I hope you can help me! thanks in advance :)
Sorry if my english is bad but i'm french, not english !
In messageCreate.js, you call your command with the following:
// 3 arguments
await cmd.run(bot, message, args);
However, your command's run function is defined with 4 parameters:
async (bot, message, config, args) => {
// config = 'args', and args = undefined
}
To fix the issue, either:
Pass in a value for config, such as null:
await cmd.run(bot, message, null, args);
Make your function only have 3 parameters:
async (bot, message, args) => {
// ...
}

Delete the latest message of the bot in dms

I have a command where the bot sends a message to a specific user trough private messages. Now I want that I can delete the last message of the bot in DMs when there is like an error or something.
What I come up with is this:
module.exports = {
name: 'dmdelete',
aliases: ['dmerase'],
description: 'Deletes last DM Bot Message.',
usage: '<user>',
staff: true,
execute(message, args) {
const mentionedMember = message.mentions.members.first().id
const User = client.users.fetch(mentionedMember)
try {
if (!mentionedMember) {
return respond('', 'Bitte erwähne einen Nutzer.', message.channel)
}
User.dmChannel.messages.fetch( {limit: 1} )
.then(messages => {
let lastMessage = messages.first();
if (!lastMessage.author.bot) return;
lastMessage.delete()
});
} catch (error) {
console.error('an error has occured', error);
}
}
}
The error that I'm getting now is:
TypeError: Cannot read property 'messages' of undefined
And yes, I have direct messages with the bot.
Anyone knows what I did wrong?
There are a couple of errors. First, users.fetch and dmChannel.messages.fetch both return a promise, so you'll need for them to be resolved.
In your code above, User is a pending Promise that has no dmChannel property. As it has no dmChannel prop (i.e. it's undefined), you can't read its messages property and you will receive TypeError: Cannot read property 'messages' of undefined.
After you fixed these problems with fetch, there could be another error with the dmChannel. Sometimes (or most of the times?), user.dmChannel returns null. To avoid this, you can create a DM channel first using the createDM() method. It also returns a promise, so you will need to resolve it first :)
Check out the working code below:
module.exports = {
name: 'dmdelete',
aliases: ['dmerase'],
description: 'Deletes last DM Bot Message.',
usage: '<user>',
staff: true,
async execute(message, args) {
const mentionedUser = message.mentions.users.first();
if (!mentionedUser)
return respond('', 'Bitte erwähne einen Nutzer.', message.channel);
const user = await client.users.fetch(mentionedUser.id);
const dmChannel = user.dmChannel || (await user.createDM());
try {
const messages = await dmChannel.messages.fetch({ limit: 1 });
let lastMessage = messages.first();
if (!lastMessage.author.bot) return;
lastMessage.delete();
} catch (error) {
console.error('an error has occured', error);
}
},
};

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of Object

I am using the source code from a security rules tutorial to attempt to do integration testing with Jest for my Javascript async function async_create_post, used for my firebase HTTP function create_post The files involved has a directory structure of the following:
Testing file: root/tests/handlers/posts.test.js
File to be tested: root/functions/handlers/posts.js
Helper code from the tutorial: root/tests/rules/helpers.js
And here is the source code that is involved:
posts.test.js
const { setup, teardown} = require("../rules/helpers");
const {
async_get_all_undeleted_posts,
async_get_post,
async_delete_post,
async_create_post
} = require("../../functions/handlers/posts");
describe("Post Creation", () => {
afterEach(async () => {
await teardown();
});
test("should create a post", async () => {
const db = await setup();
const malloryUID = "non-existent uid";
const firstPost = {
body: "First post from Mallory",
author_id: malloryUID,
images: ["url1", "url2"]
}
const before_post_snapshot = await db.collection("posts").get();
expect(before_post_snapshot.docs.length).toBe(0);
await async_create_post(firstPost); //fails at this point, expected to create a new post, but instead threw an error
const after_post_snapshot = await db.collection("posts").get();
expect(after_post_snapshot.docs.length).toBe(1);
});
});
posts.js
const {admin, db } = require('../util/admin');
//admin.initializeApp(config); //my credentials
//const db = admin.firestore();
const { uuid } = require("uuidv4");
const {
success_response,
error_response
} = require("../util/validators");
exports.async_create_post = async (data, context) => {
try {
const images = [];
data.images.forEach((url) => {
images.push({
uid: uuid(),
url: url
});
})
const postRecord = {
body: data.body,
images: images,
last_updated: admin.firestore.FieldValue.serverTimestamp(),
like_count: 0,
comment_count: 0,
deleted: false,
author_id: data.author_id
};
const generatedToken = uuid();
await db
.collection("posts")
.doc(generatedToken)
.set(postRecord);
// return success_response();
return success_response(generatedToken);
} catch (error) {
console.log("Error in creation of post", error);
return error_response(error);
}
}
When I run the test in Webstorm IDE, with 1 terminal running Firebase emulators:start , I get the following error message.
console.log
Error in creation of post TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received an instance of Object
at validateString (internal/validators.js:120:11)
at Object.basename (path.js:1156:5)
at GrpcClient.loadProto (/Users/isaac/Desktop/project/functions/node_modules/google-gax/src/grpc.ts:166:23)
at new FirestoreClient (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/v1/firestore_client.js:118:38)
at ClientPool.clientFactory (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/index.js:330:26)
at ClientPool.acquire (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/pool.js:87:35)
at ClientPool.run (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/pool.js:164:29)
at Firestore.request (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/index.js:961:33)
at WriteBatch.commit_ (/Users/isaac/Desktop/project/functions/node_modules/#google-cloud/firestore/build/src/write-batch.js:485:48)
at exports.async_create_post (/Users/isaac/Desktop/project/functions/handlers/posts.js:36:5) {
code: 'ERR_INVALID_ARG_TYPE'
}
at exports.async_create_post (/Users/isaac/Desktop/project/functions/handlers/posts.js:44:13)
Error: expect(received).toBe(expected) // Object.is equality
Expected: 1
Received: 0
<Click to see difference>
at Object.<anonymous> (/Users/isaac/Desktop/project/tests/handlers/posts.test.js:59:45)
Error in creation of post comes from the console.log("Error in creation of post", error); in posts.js, so the error is shown in the title of this post.
I want to know why calling the async_create_post from posts.test.js will cause this error and does not populate my database with an additional record as expected behaviour. Do inform me if more information is required to solve the problem.
Here are some code snippets that may give more context.
helpers.js [Copied from the repository]
const firebase = require("#firebase/testing");
const fs = require("fs");
module.exports.setup = async (auth, data) => {
const projectId = `rules-spec-${Date.now()}`;
const app = firebase.initializeTestApp({
projectId,
auth
});
const db = app.firestore();
// Apply the test rules so we can write documents
await firebase.loadFirestoreRules({
projectId,
rules: fs.readFileSync("firestore-test.rules", "utf8")
});
// write mock documents if any
if (data) {
for (const key in data) {
const ref = db.doc(key); // This means the key should point directly to a document
await ref.set(data[key]);
}
}
// Apply the actual rules for the project
await firebase.loadFirestoreRules({
projectId,
rules: fs.readFileSync("firestore.rules", "utf8")
});
return db;
// return firebase;
};
module.exports.teardown = async () => {
// Delete all apps currently running in the firebase simulated environment
Promise.all(firebase.apps().map(app => app.delete()));
};
// Add extensions onto the expect method
expect.extend({
async toAllow(testPromise) {
let pass = false;
try {
await firebase.assertSucceeds(testPromise);
pass = true;
} catch (error) {
// log error to see which rules caused the test to fail
console.log(error);
}
return {
pass,
message: () =>
"Expected Firebase operation to be allowed, but it was denied"
};
}
});
expect.extend({
async toDeny(testPromise) {
let pass = false;
try {
await firebase.assertFails(testPromise);
pass = true;
} catch (error) {
// log error to see which rules caused the test to fail
console.log(error);
}
return {
pass,
message: () =>
"Expected Firebase operation to be denied, but it was allowed"
};
}
});
index.js
const functions = require('firebase-functions');
const {
async_get_all_undeleted_posts,
async_get_post,
async_delete_post,
async_create_post
} = require('./handlers/posts');
exports.create_post = functions.https.onCall(async_create_post);
The error message means that a method of the path module (like path.join) expects one of its arguments to be a string but got something else.
I found the offending line by binary search commenting the program until the error was gone.
Maybe one of your modules uses path and you supply the wrong arguments.

How to trouble shoot "NaN" error when the call to a function and assigning to let is the only visible issue

I'm testing an Alexa skill locally and getting an error that just says NaN. I have figured out that line let recipe = getRecipe() is the problem through console.log() statements. It doesn't appear to be in the the getRecipe() function itself because a console.log() statement at the very beginning of the try block in that function does not run, but the one at the beginning of the catch does. Thanks in advance for any suggestions.
Handler:
handle(handlerInput){
const attributes = handlerInput.attributesManager.getSessionAttributes();
const request = handlerInput.requestEnvelope.request;
switch (attributes.previousIntent){
case "FoodIntent":
if(request.intent.slots.answer.resolutions.resolutionsPerAuthority[0].values[0].value.name === 'yes'){
let randomFood = Helpers.suggestFood(handlerInput);
let queryFood = randomFood.replace(/\s+/g, '-').toLowerCase(); event
attributes.currentSuggestedFood = queryFood;
const speechText = 'Great! In the future I will be able to look up the ingredients for you.'
console.log('before call getRecipe()')
let recipe = getRecipe(handlerInput)
console.log('After call getRecipe()')
return handlerInput.responseBuilder
.speak(speechText + " "+ recipe)
.reprompt(speechText)
.withShouldEndSession(true)
.withSimpleCard('Cheer Up - YesNo', speechText)
.getResponse();
} else {
let randomFood = Helpers.suggestFood(handlerInput);
let speechText = ResponseToUsersNo[Math.floor(Math.random() * ResponseToUsersNo.length)]+
FoodPrefixes[Math.floor(Math.random() * FoodPrefixes.length)] +
randomFood + FoodSuffixes[Math.floor(Math.random() * FoodSuffixes.length)];
let repromptText = 'Did the last suggestion work for you?'
handlerInput.attributesManager.setSessionAttributes(attributes);
if (attributes.FoodsAlreadySuggested.length >= 10) {
speechText = 'I feel like you don\'t actually want anything. So I\'m leaving for now, talk to you later.'
return handlerInput.responseBuilder
.speak(speechText)
.withShouldEndSession(true)
.withSimpleCard('Cheer Up - YesNo', speechText)
.getResponse();
}
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(repromptText)
.withSimpleCard('Cheer Up - YesNo', speechText)
.getResponse();
}
case "HobbyIntent":
if(request.intent.slots
And the getRecipe() function:
async function getRecipe(handlerInput) {
try{
console.log('before attributes')
const attributes = handlerInput.attributesManager.getSessionAttributes();
console.log('attributes: '+ attributes)
console.log('before url')
const url = `https://api.edamam.com/search?q=${attributes.currentSuggestedFood}&app_id=${FOOD_APP_ID}&app_key=${FOOD_APP_KEY}`; //&from=0&to=3&calories=591-722&health=alcohol-free this was on the end of the uri
console.log(url)
console.log('after url')
request.get(url, (error, response, body) => {
// let json = JSON.parse(body);
console.log('error:', error); // Print the error if one occurred
console.log('statusCode:', response && response.statusCode); // Print the response status code if a response was received
console.log('body:', body); // Print the body
//const theRecipe = await body;
const payload = JSON.parse(body)
console.log("The ingredients for "+ payload.q + " is: ")
console.log(payload.hits[0].recipe.ingredientLines)
return (payload.hits[0].recipe.ingredientLines);
});
}
catch(err){
console.log('before error statement in catch')
console.error('There was an error: ', + err)
}
};
Here is my output:
before call getRecipe()
before attributes
attributes: [object Object]
before url
https://api.edamam.com/search?q=rellenos-de-papa&app_id=b4dbea92&app_key=8d916c99b930b77c8cbb4615f0800df7
after url
before error statement in catch
There was an error: NaN
After call getRecipe()
{ version: '1.0',
response:
{ outputSpeech:
{ type: 'SSML',
ssml: '<speak>Great! In the future I will be able to look up the ingredients for you. The ingredients are [object Promise]</speak>' },
reprompt: { outputSpeech: [Object] },
shouldEndSession: true,
card:
{ type: 'Simple',
title: 'Cheer Up - YesNo',
content: 'Great! In the future I will be able to look up the
ingredients for you.' } },
userAgent: 'ask-node/2.3.0 Node/v8.12.0',
sessionAttributes:
{ foodType: 'PuertoRican',
FoodsAlreadySuggested: [ 'Platanos Maduros', 'Rellenos de Papa' ],
previousIntent: 'FoodIntent',
state: '_YES_NO',
currentSuggestedFood: 'rellenos-de-papa' } }
UPDATE:
#Shilly. So I'm still confused... An aside, I had to edit your function a bit to make the code inside the catch reachable... but anyway I think what I did still retains the core logic you were trying to impart.
My problem is that I get an error when I parse that says unexpected token o in JSON at position 1. I think this usually means I don't need to parse it because it's already a valid js object. Cool. So I remove the parse, but then I get Cannot read property '0' of undefined., referring of course to my return payload.hits[0].recipe.ingredientLines. Can't seem to wrap my head around why. Thanks a bunch for your help.
function getRecipe(handlerInput) {
const attributes = handlerInput.attributesManager.getSessionAttributes();
const url = `https://api.edamam.com/search?q=${attributes.currentSuggestedFood}&app_id=${FOOD_APP_ID}&app_key=${FOOD_APP_KEY}`; //&from=0&to=3&calories=591-722&health=alcohol-free this was on the end of the uri
return get( url, ( response, body ) => {
const payload = JSON.parse(body)
console.log(payload)
return payload.hits[0].recipe.ingredientLines;
}).catch( error => {
console.error( `failed GET request for: ${ url }` );
console.error( error );
});
};
Also here is the beginning of the body in the response, which doesn't look parsed to me... body: '{\n "q" : "tostones",\n "from" : 0,\n "to" : 10,\n "params" : {\n
Finally figured it out. Many thanks to #Shilly for guiding me in the proper direction. My understanding of async and await was wrong. These sources were helpful:
Returning handler.ResponseBuilder from promise.then() method
https://medium.com/#tkssharma/writing-neat-asynchronous-node-js-code-with-promises-async-await-fa8d8b0bcd7c
Here is my updated code:
The async handler relies on a function that I created to use Promises with #Shilly's help. It's probably not the most concise way, but it works!
Handler:
async handle(handlerInput){
const attributes = handlerInput.attributesManager.getSessionAttributes();
const request = handlerInput.requestEnvelope.request;
switch (attributes.previousIntent){
case "FoodIntent":
if(request.intent.slots.answer.resolutions.resolutionsPerAuthority[0].values[0].value.name === 'yes'){
let randomFood = Helpers.suggestFood(handlerInput);
let queryFood = randomFood.replace(/\s+/g, '-').toLowerCase();
attributes.currentSuggestedFood = queryFood;
const speechText = 'Great! Here are the ingredients!'
let recipe = await getRecipe(handlerInput)
let recipeIngredients = recipe.hits[0].recipe.ingredientLines;
return handlerInput.responseBuilder
.speak(speechText+ 'The ingredients are '+ recipeIngredients)
.reprompt(speechText)
.withShouldEndSession(true)
.withSimpleCard('Cheer Up - YesIntentFood', recipeIngredients)
.getResponse();
function:
async function getRecipe(handlerInput) {
const attributes = handlerInput.attributesManager.getSessionAttributes();
const url = `https://api.edamam.com/search?q=${attributes.currentSuggestedFood}&app_id=${FOOD_APP_ID}&app_key=${FOOD_APP_KEY}`;
console.log(url)
return new Promise (function(resolve, reject) {
request.get(url, (error, response, body) => {
if (error) {
reject(error);
} else {
resolve(JSON.parse(body))
}
});
})
};
Output:
https://api.edamam.com/search?q=pernil&app_id=b4dbea92&app_key=8d916c99b930b77c8cbb4615f0800df7
{ version: '1.0',
response:
{ outputSpeech:
{ type: 'SSML',
ssml: '<speak>Great! In the future I will be able to look up the ingredients for you.The ingredients are 2 1/2 pounds pork shoulder, boston butt, pernil,2 garlic cloves,1 small onion,1 bunch cilantro,1 jalapeño,1 cup orange juice,1 cup pineapple juice,1 lemon,Handfuls salt,Pepper to taste,Ground cumin</speak>' },
reprompt: { outputSpeech: [Object] },
shouldEndSession: true,
card:
{ type: 'Simple',
title: 'Cheer Up - YesIntentFood',
content: [Array] } },
userAgent: 'ask-node/2.3.0 Node/v8.12.0',
sessionAttributes:
{ foodType: 'PuertoRican',
FoodsAlreadySuggested: [ 'Platanos Maduros', 'Pernil' ],
previousIntent: 'FoodIntent',
state: '_YES_NO',
currentSuggestedFood: 'pernil' } }
const attributes = handlerInput.attributesManager.getSessionAttributes() throws an error NaN for reasons still unknown.
The catch() handler catches this error and logs it.
But since the function is async, and you don't resolve the promise inside the catch clause, you get this [object Promise] stringified version of that promise instead of the actual ingredient list.
Edit:
Have you considered using util.promisify() so you don't have to mix callbacks and promises?
const { promisify } = require( 'util' );
const request = require( 'request' );
const get = promisify( request.get );
function getRecipe(handlerInput) {
const attributes = handlerInput.attributesManager.getSessionAttributes();
const url = `https://api.edamam.com/search?q=${attributes.currentSuggestedFood}&app_id=${FOOD_APP_ID}&app_key=${FOOD_APP_KEY}`; //&from=0&to=3&calories=591-722&health=alcohol-free this was on the end of the uri
return get( url, ( response, body ) => {
const payload = JSON.parse(body)
return payload.hits[0].recipe.ingredientLines;
}).catch( error ) {
console.error( `failed GET request for: ${ url }` );
console.error( error );
});
};
Same can be written with async/await style, but I'm not fluent enough in it to get it 100% correct without being able to test the code myself.

Categories

Resources