I have a json, viewable at https://imgur.com/a/F3kV29F
or here https://dweet.io/get/dweets/for/shyam__5
In python, I am able to print the yearlyWatts by doing:
print(collection[1]['content']['yearlyWatts'])
where collection is the json, done by:
collection = (dweepy.get_dweets_for('shyam__5'))
I am trying to do the same thing in Javascript. Currently, I have done:
getCryptoCurrencyInfo(5)
.then(currencyInfo => {
console.log(currencyInfo[1].yearlyWatts)
This does not work, I get no output.
Please do not pay attention to the function getCryptoCurrencyInfo, I would really appreciate if someone could tell me what to write in the console.log(HERE) in order to output the yearly watts of 111255.51
Any help would be appreciated. Thanks!
Suppose you want a single yearlyWatt.
const data = {
"this": "succeeded",
"by": "getting",
"the": "dweets",
"with": [{
"thing": "shyam__5",
"created": "2020-07-03T08:38:01.184Z",
"content": {
"test": "test"
}
},
{
"thing": "shyam__5",
"created": "2020-07-03T08:37:58.068Z",
"content": {
"yearlyWatts": 111429.4
}
}
]
}
console.log(data.with[1].content.yearlyWatts)
I figured out how to do it thanks to xMayank's help.
In the backend module, the code is:
import { fetch } from 'wix-fetch'
export function getCryptoCurrencyInfo() {
const url = 'https://dweet.io/get/dweets/for/shyam__5'
console.log(url)
return fetch(url, { method: 'get' }).then(response => response.json())
}
To get it to work, the site page (front end) says this:
// For full API documentation, including code examples, visit https://wix.to/94BuAAs
import { getCryptoCurrencyInfo } from 'backend/serviceModule'
import { fetch } from 'wix-fetch'
$w.onReady(function() {
//TODO: write your page related code here...
getCryptoCurrencyInfo().then(currencyInfo => {
const data = currencyInfo
console.log(data.with[1].content.yearlyWatts)
console.log(data.with[2].content.monthlyWatts)
console.log(data.with[3].content.currentDailyCarbonSaved)
console.log(data.with[4].content.currentDailyWatts)
})
})
considering global_obj your json_object, you can do this
global_obj.with.find(element => element.thing==="shyam__5");
Related
I'm trying to understand why Jest is not allowing me to import functions from _mocks_/http.js.
This is my catchAnalysis.js file
import { fetchNewsData } from './http'
async function catchAnalysis(params) {
console.log("::: Form Submitted :::")
fetchNewsData(params)
.then(response => /* Blablabla */)
.catch(error => console.log('error', error));
}
This works great. Below is my catchAnalysis.test.js file:
jest.mock('./http')
import { fetchNewsData } from './http'
test("Mock API works", () =>{
let testing = fetchNewsData()
console.log(`fetchNewsData value is ${testing}`)
/* Blablabla */
})
fetchNewsData() is undefined when I run JEST tests with npm.
Am I using jest.mock('') incorrectly? I don't know where to start to debug.
For context, this is the _mocks_/http.js file. The real file is a simple fetch API call.
function fetchNewsData(){
console.log("::: MOCK API :::")
let responseData = {
"agreement": "DISAGREEMENT",
"confidence": "86",
"irony": "NONIRONIC",
"model": "general_en",
"score_tag": "P",
"status": {
"code": "0",
"msg": "OK",
"credits": "3",
"remaining_credits": "19849"
},
"subjectivity": "SUBJECTIVE"
}
console.log(`response Text is ${response.text()}`)
return Promise.resolve(response)
}
export {
fetchNewsData
}
Thank you!
I found the answer...
Misread document -> the mock folder has to be in the same directory as the file being mocked. I had put it in src.
I didn't expect folder location to be the issue!
I am using cypress.io to test an API(Created using Node.js). I want to extract value from JSON response of the API and save it to a variable.
I have tried solutions mentioned in the below links it did not work:
Cypress - get value from json response body
Below is the code i am using to test the API:
/// <reference types="cypress" />
describe("Testing Provider Catalog API", () => {
it("Provider Catalog API GET Request", () => {
cy.request('GET', 'v1/providers')
.then((response) => {
expect(response).to.have.property('status', 200)
expect(response.body).to.not.be.null
// expect(response.body.providers).to.have.length(1)
})
cy.screenshot()
})
it("Provider Catalog API POST Request", () => {
const provider = {
"type": "loadboard",
"name": "123loadboard"
};
cy.request('POST', 'v1/providers', provider)
cy.screenshot()
})
it("Provider Catalog API PUT Request", () => {
const provider = {
"type": "loadboard",
"name": "123loadboard"
};
cy.request('PUT', 'v1/providers/61a54a66a2b734859481931c', provider)
cy.screenshot()
})
it("Provider Catalog API DELETE Request", () => {
cy.request('DELETE', 'v1/providers/61a68e7ca6011e605029191b')
cy.screenshot()
})
})
Below is the code that i am using
var providerId
cy.wait('#newObject').then((response) => {
expect(response.status).to.eq(201)
expect(response.responseBody).to.have.property('_id')
const body = (response.responseBody)
providerId = body['_id']
})
cy.get(someInput).type(newId)
Sample output of the API:
{
"_id":"61a54ba1a2b7348594819323",
"type":"loadboard",
"name":"123loadboard",
"__v":0
}
I want to store the value of the _id in a variable and use it later. I have been trying to for the last couple of days and nothing seems to work. Can anyone please help me. Thanks in advance.
The recommended way to use variables with cypress is with aliases. See docs here.
In your code, you can wrap() your _id and save it as an alias, then call your alias somewhere else in your code:
cy.wait('#newObject').then((response) => {
expect(response.status).to.eq(201)
expect(response.responseBody).to.have.property('_id')
cy.wrap(response.responseBody._id).as('newId')
})
// then later in your code use:
cy.get('#newId').then((newId) => {
cy.get(someInput).type(newId)
})
You could also type() your _id inside your wait():
cy.wait('#newObject').then((response) => {
expect(response.status).to.eq(201)
expect(response.responseBody).to.have.property('_id')
cy.get(someInput).type(response.responseBody._id)
})
Or you can use cypress global environmment object Cypress.env(). See docs here.
cy.wait('#newObject').then((response) => {
expect(response.status).to.eq(201)
expect(response.responseBody).to.have.property('_id')
Cypress.env('newId', response.responseBody._id)
})
// then later in your code use:
cy.get(someInput).type(Cypress.env('newId'))
I want to define the response structure of my requests in the simplest way, and the first thing that comes in my mind to do this is a middleware.
My endpoints are returning the response content correctly:
{{base_url}}/users returns a list of users:
{
[
{
"id": 44,
"name": "some name"
[...]
}
]
}
What I want to do (in all requests) is to add the fields status and data (or any other I'd like to add), like this:
{
"status": 200,
"data": [
{
"id": 44,
"name": "some name"
[...]
}
]
}
I've created a middleware that waits for the resolution but I'm not able to get the content nor add some property to it.
[...]
async handle ({request, response}, next) {
await next()
const content = response._lazyBody.content
content.status = response.response.statusCode
}
[...]
I know this will not work but I want something similar to this. I've looked in Adonis docs and forum, but no answers fit to my needs.
Any help will be welcome
You can extend Response By extending the core. The simplest way is to create a file inside start folder and name it hooks.js and copy and paste the content below inside it:
const { hooks } = use('#adonisjs/ignitor')
const Response = use('Adonis/Src/Response')
hooks.after.providersBooted(() => {
Response.macro('customJson', function (status, data) {
this.status(status).json({
status,
data
})
})
})
this piece of code extends the Response module and add customJson method to it which takes two arguments, status and data, and send them back to the client.
And here you can see how to use it:
Route.get('/users', async ({ response }) => {
let status = ''// whatever you want
let data = ''// whatever you want
return response.customJson(status, data)
})
Im tring to read a simple setting from a json file, the json is this :
{
"Label": "some string here"
}
form my javascript part i do:
import settings from '../settings.json';
then:
var settings= ()=> {
const headers = new Headers();
const requestOptions = {
method: 'GET',
headers: { ...headers.authentication, ...headers.culture, 'ContentType':'application/json',
};
return fetch(`${settings.Label}`, requestOptions).then(() => {
return response.text().then(text => {
const data = text ? text && JSON.parse(text) : {};
let token = response.headers.get('X-Token');
if (token) {
data.token = token;
}
if (!response.ok) {
// manage error here
}
return Promise.reject(error);
}
return data;
})
});
};
// use settings here
Despite my many searches and attempts im not very expert in javascript,i have tried in many ways before, but the my variable 'settings' is not contain nothing.
I believe you need to add an export to your JSON file
export const settings = {
"label": "some string here"
}
Not much information given here, but this probably has to do with transpiling your javascript. You can use:
const settings = require('../settings.json')
instead.
try this answer https://stackoverflow.com/a/59844868/7701381
Also, change the name of the imported json settings or the var settings, cuz this might cause unexpected behaviors
I had completely wrong the approach, the file is already available and I don't have to request to download it from the server, I just have to return string, without use of fetch or other:
return (`${settings.Label}`
Sorry and thank a lot for the support
I am trying to use the Fetch API with my Rails application. I can pass parameters to the controller as part of a query string, but still can't figure out how to pass JSON data or where to find it in the controller. A sample call looks like the below. Where can I access my test data on in the controller? Happy Sunday :)
export const fetchControllerData = () => {
return fetch('api/users',), {
body: { "test": "test" }
})
.then(res => res.json());
};
I'm in the process of working out my own issues with fetch and Rails. But I'll take a stab at this.
I expect that fetch is using GET as the default method - which won't use the body at all. You will likely need to set the method to be POST to get the body through. Further to that you might need to set the Content-Type header (to application/json) in order to send the data through as JSON.
May be u need to send params in this way for get request and use this link for https://github.com/axios/axios
export const fetchControllerData = () => {
params = { body: { "test": "test" } }
return HTTP.get('api/users', params)
.then((response) => {
if (response.success) {
// do something here
} else {
// handle error condtion here
}
});
}