Unable to update Data - rest

Am trying to update the json data through an api call.
I was able to GET the data without any issues, as am not passing any Options in the request.
For UPDATE,
//saga.js
export function* BlurideaTitler(opt) {
const id = opt.id; // 4
const updatedTitle = opt.newTitle; // "title changed"
let options = {
crossDomain: true,
method: 'PUT',
json: true,
headers: {'Content-Type': 'application/json'},
body: {
title: updatedTitle
}
};
const requestURL = `http://localhost:3000/ideas/${id}`;
try {
yield call(request, requestURL, options);
} catch (err) {
console.log(err);
}
}
// request.js
export default function request(url, options) {
return fetch(url, options)
.then(checkStatus)
.then(parseJSON);
}
//db.json
JSON am trying to update.,
{
"ideas": [
{
"id": 4,
"title": "My fourth Idea",
"body": "Description of my fourth idea",
"created_date": "14-Apr-2019"
}
]
}
This is supposed to update the value of title. But it throws error'Bad request' . Can someone please let me know what am missing here.

Related

How to implement the google translator api in the dialogflow line editor

I am having problems when implementing a translator in dialogflow, I don't know what will be wrong, the code does not work for me. could you please guide me. I clarify that the line editor does not let me implement an asynchronous function.
const axios = require('axios');
const unirest = require('unirest');
const functions = require('firebase-functions');
const {WebhookClient} = require('dialogflow-fulfillment');
const {Card, Suggestion} = require('dialogflow-fulfillment');
process.env.DEBUG = 'dialogflow:debug'; // enables lib debugging statements
exports.dialogflowFirebaseFulfillment = functions.https.onRequest((request, response) => {
const agent = new WebhookClient({ request, response });
console.log('Dialogflow Request headers: ' + JSON.stringify(request.headers));
console.log('Dialogflow Request body: ' + JSON.stringify(request.body));
function translate(agent){
const text = agent.parameters.text;
const key = "yout_key";
const to = 'es';
const from = 'en';
const response = axios.post(`https://www.googleapis.com/language/translate/v2?key=${key}&source=${from}&target=${to}&q=${text}`);
return response.then((result) => {
console.log(result.text);
agent.add("traduccion: "+result.text);
});
}
let intentMap = new Map();
intentMap.set('traducir', translate);
agent.handleRequest(intentMap);
});
this is the Diagnostic info that I get in the Raw API response
{
"responseId": "7ecceeb9-9764-417a-9899-315dca16b550-b03aa3f9",
"queryResult": {
"queryText": "hello",
"parameters": {
"text": "hello"
},
"allRequiredParamsPresent": true,
"fulfillmentText": "traduccion: undefined",
"fulfillmentMessages": [
{
"text": {
"text": [
"traduccion: undefined"
]
}
}
],
"outputContexts": [
{
"name": "projects/canvas-primacy-314603/agent/sessions/d5048480-e5fb-c291-19d7-a2085d8d5fe2/contexts/text",
"lifespanCount": 5,
"parameters": {
"text.original": "hello",
"text": "hello"
}
}
],
"intent": {
"name": "projects/canvas-primacy-314603/agent/intents/b4144ec2-afd1-46bd-9347-7e20ae615f58",
"displayName": "traducir"
},
"intentDetectionConfidence": 1,
"diagnosticInfo": {
"webhook_latency_ms": 3292
},
"languageCode": "en",
"sentimentAnalysisResult": {
"queryTextSentiment": {
"score": 0.2,
"magnitude": 0.2
}
}
},
"webhookStatus": {
"message": "Webhook execution successful"
}
}
Before running the code I set up my intent to translate words after the colon (:).
In your code, to properly get the response you should be using result.data to get the body of the response. The body of the response is structured this way:
{
"data":{
"translations":[
{
"translatedText":"translated_output_here"
}
]
}
}
Thus you can access the translated data by printing this result.data.data.translations[0].translatedText.
const text = agent.parameters.any; // This is based from my intent I used "any" as entity of words typed after the colon (:)
const key = "your_api_key";
const to = 'es';
const from = 'en';
const response = axios.post(`https://www.googleapis.com/language/translate/v2?key=${key}&source=${from}&target=${to}&q=${text}`);
return response.then((result) => {
console.log(result.data.data.translations[0].translatedText);
output = result.data.data.translations[0].translatedText;
agent.add("traduccion: "+ output);
});
}
Testing done:
There are some issues with the code. The code needs to require the needed libraries, to define agent, to include an intent map, and the function must be named dialogflowFirebaseFulfillment to use the Dialogflow fulfillment library.
You can see the Dialogflow fulfillment library docs and samples to see the required boilerplate elements 1 then add your code around them.

How to format axios GET call with nested params

I want to fetch an API
The call look like this;
const instance = axios.create({
method: 'GET',
uri: 'https://api.compound.finance/api/v2/account',
timeout: timeout,
params: {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
},
},
headers: {
"Content-Type": "application/json",
},
});
The API spec https://compound.finance/docs/api
{
"addresses": [] // returns all accounts if empty or not included
"block_number": 0 // returns latest if given 0
"max_health": { "value": "10.0" }
"min_borrow_value_in_eth": { "value": "0.002" }
"page_number": 1
"page_size": 10
}
However the output URI contains some character to replace { } arround max_health value
The uri end up looking like this;
/api/v2/account?block_number=0&page_number=1&page_size=250&max_health=%7B%22value%22:%221%22%7D'
I have tried qs but it's not working as I expect.
I have tryed this to ;
let params = {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
}
}
await instance.get('https://api.compound.finance/api/v2/account',JSON.stringify(params)).then( (response) => {...})
It gave me this error ;
TypeError: Cannot use 'in' operator to search for 'validateStatus' in
{"block_number":"0","page_number":"1","page_size":"250","max_health":{"value":"1"}}
Any help would be appreciated.
The fix;
Use paramSerializer
const instance = axios.create({
method: 'GET',
uri: 'https://api.compound.finance/api/v2/account',
timeout: timeout,
params: {
block_number:'0',
page_number:'1',
page_size:'250',
max_health: {
value:'1'
},
},
paramsSerializer: function (params) {
return Qs.stringify(params, {arrayFormat: 'brackets'})
},
headers: {
"Content-Type": "application/json",
},
});

(intermediate value).sendEmail(...).promise is not a function

I'm using aws-sdk in my service to send emails. I'm getting below exception to a code which was working fine before.
const aws = require('aws-sdk');
var params = {
Destination: {
ToAddresses: [
'checkMail#gmail.com'
]
},
Message: {
Body: {
Html: {
Charset: "UTF-8",
Data: "HTML_FORMAT_BODY"
},
Text: {
Charset: "UTF-8",
Data: "this is sample"
}
},
Subject: {
Charset: 'UTF-8',
Data: 'Test email'
}
},
Source: 'AWS Services<awsEmails#awsService.com>'
ReplyToAddresses: [
'AwsServices<noreply#awsServices.com>'
],
};
// Create the promise and SES service object
var emailPromise = new aws.SES({apiVersion: '2010-12-01'}).sendEmail(params).promise();
// Handle promise's fulfilled/rejected states
emailPromise.then(
function(data) {
//my logic on success goes here
}).catch(
function(err) {
//my logic on error goes here
});
I have tried using different API calls for email from AWS but all returns the same error.
Avoid require ALL aws-sdk if it's just to use a single service. For using SES, you can yarn add #aws-sdk/client-ses and then use it const { SESClient, SendEmailCommand } = require("#aws-sdk/client-ses");
I show you here a full exemple of sending email with SES in a nodeJS lambda function:
const {
SESClient,
SendEmailCommand,
} = require("#aws-sdk/client-ses");
const REGION = "eu-west-3"; // Use you AWS region
const ses = new SESClient({ region: REGION });
exports.handler = async function (event) {
const path = event.path;
if (path === "/send-email") {
const peopleAmount = 12;
const params = {
Source: "John Wick <john.wick#killer.com>",
Destination: {
ToAddresses: ["adresse1#test.com"],
},
Message: {
Body: {
Html: {
Data: `<span>This email is about <b>${peopleAmount}</b> people.</span>`,
},
},
Subject: {
Data: "Email Title",
},
},
};
try {
const data = await ses.send(new SendEmailCommand(params));
return {
statusCode: 200,
body: peopleAmount,
};
} catch (e) {
console.error(e, e.stack);
return {
statusCode: 400,
body: "Sending failed",
};
}
}
}
I hope it helps, here is documentation to use SES email template.

Mongoose schema optional with validation

Given a Schema like this:
new Schema(
{
someData: {
someString: {
required: false,
maxlength: 400,
type: String
}
otherData: {
required: true,
type: String
}
});
someString is optional but has a validation to check if it's length is below 400.
If I'm given an invalid length string (>400) would this object still be saved but without the someString or would this throw an error? If this throws an error how can I change the schema so that the object will still get saved?
It will throw an error without saving the document.
Let's say we have this schema:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const studentSchema = new Schema({
someData: {
someString: {
required: false,
maxlength: 5,
type: String
},
otherData: {
required: true,
type: String
}
}
});
module.exports = mongoose.model("Student", studentSchema);
And this post route:
const Student = require("../models/student");
router.post("/students", async (req, res) => {
try {
const result = await Student.create(req.body);
res.send(result);
} catch (err) {
console.log(err);
if (err.name === "ValidationError") {
return res.status(400).send(err.errors);
}
res.status(500).send("Something went wrong");
}
});
When we send a bad request it will give ValidationError where we can read the error details from err.errors.
Request Body:
{
"someData": {
"someString": "123456",
"otherData": "other"
}
}
The response will be:
{
"someData.someString": {
"message": "Path `someData.someString` (`123456`) is longer than the maximum allowed length (5).",
"name": "ValidatorError",
"properties": {
"message": "Path `someData.someString` (`123456`) is longer than the maximum allowed length (5).",
"type": "maxlength",
"maxlength": 5,
"path": "someData.someString",
"value": "123456"
},
"kind": "maxlength",
"path": "someData.someString",
"value": "123456"
}
}
You can resolve this by removing the maxlength option, or check the field's length in your route, and if it's length is bigger than the specified maxlength, you can substr it so that it doesn't result in error.
router.post("/students", async (req, res) => {
try {
let doc = req.body;
if (doc.someData && doc.someData.someString && doc.someData.someString.length > 5) {
doc.someData.someString = doc.someData.someString.substring(0, 5);
}
const result = await Student.create(doc);
res.send(result);
} catch (err) {
console.log(err);
if (err.name === "ValidationError") {
return res.status(400).send(err.errors);
}
res.status(500).send("Something went wrong");
}
});

Loopback 4 - POST request dtasource template

I am having issue to declare POST operation in Loopback 4 datasource file.
My template is as follows:
{
"template": {
"method": "POST",
"url": "https://reqres.in/api/login"
},
"functions": {
"login": []
}
}
My service interface
login(email: string, password: string): Promise<any>;
My Controller
#post('/loginTest')
async testingLogin(
#requestBody({
content: {
'application/json': {
schema: getModelSchemaRef(TestModel, {
title: 'Post',
}),
},
},
})
testModel: TestModel, )
: Promise<any> {
// TEST MODEL CONTAIN JSON OBJECT {email: "" , password: ""}
console.log("Test Model Representation: ", testModel)
try {
var response = await this.loginService.login(testModel.email, testModel.password);
} catch (error) {
console.log("error", error)
}
console.log("Fake POST response", response)
return response;
};
I am using this fake API : https://reqres.in/api/login
I am getting following error:
Test Model Representation: { email: 'string', password: 'string' }
error Error: {"error":"Missing email or username"}
at callback (D:\loginApp\node_modules\loopback-connector-rest\lib\rest-builder.js:541:21)
at D:\loginApp\node_modules\loopback-datasource-juggler\lib\observer.js:269:22
at doNotify (D:\loginApp\node_modules\loopback-datasource-juggler\lib\observer.js:157:49)
at RestConnector.ObserverMixin._notifyBaseObservers (D:\loginApp\node_modules\loopback-datasource-juggler\lib\observer.js:180:5) {
statusCode: 400,
message: '{"error":"Missing email or username"}'
}
Fake POST response undefined
It look like my email and password is not passed ? Thanks for any help.
The login function you defined in the datasource file should match with the service interface. That means it would be something like:
"functions": {
"login": ["email", "password"]
}