GraphQL/GraphCool Why do coordinates don't work with FLOAT? - function

I'm currently working on GraphQL/GraphCool wrapping a RestAPI, but when I write my resolver with Float in order to extract latitude and longitude as floats I get the following error:
"code": 5004,
"message": "Returned JSON Object does not match the GraphQL type. The field 'latitud' should be of type Float \n\n Json:
{\n \"id\": \"6115\",\n \"nombre\": \"ABARROTES LA SOLEDAD\",\n \"latitud\": \"21.85779823\",\n \"longitud\": \"-102.28161261\"\n}\n\n"
if I use String there is no problem!
RESOLVER SDL
type AbarrotesPayload {
id: ID!
nombre: String!
latitud: Float!
longitud: Float!
}
extend type Query {
feed(distancia: Int!): [AbarrotesPayload!]!
}
RESOLVER FUNCTION
"use strict";
const fetch = require("node-fetch");
const API_TOKEN = "d3bfd48a-bced-4a58-a58b-4094da934cf1";
module.exports = event => {
const distancia = event.data.distancia;
return fetch(getRestEndpoint(distancia, API_TOKEN))
.then(response => response.json())
.then(data => {
const abarrotes = [];
for (let item in data) {
abarrotes.push({
id: data[item].Id,
nombre: data[item].Nombre,
latitud: data[item].Latitud,
longitud: data[item].Longitud
});
}
console.log(abarrotes);
return { data: abarrotes };
});
};
function getRestEndpoint(query) {
return `http://www3.inegi.org.mx/sistemas/api/denue/v1/consulta/buscar/abarrotes/21.85717833,-102.28487238/${query}/${API_TOKEN}`;
}
And my Query is the following:
query {
feed(distancia: 400) {
id
nombre
latitud
longitud
}
}
By the way, im working on the graph.cool platform!

This had nothing to do with GraphQL/GraphCool, I just needed to parseFloat() the values which I'm receiving as a string, and then push it to the array.
latitud: parseFloat(data[item].Latitud),
longitud: parseFloat(data[item].Longitud)

Related

How to get data from database in array format using node js and MySql

I am using node.js as server language and Mysql as database so I am running query and getting data from database but is is showing in format like this
[ BinaryRow { name: 'Dheeraj', amount: '77.0000' },
BinaryRow { name: 'Raju', amount: '255.0000' } ]
What I want is
['Dheeraj', 77.0000],
['Raju', 66255.000030],
This what I am doing in my backend (node.js):
My model:
static getChartData(phoneNo, userType) {
let sql = 'select businessname as name,sum(billamt) amount from cashbackdispdets where consphoneno =' + phoneNo + ' group by businessid order by tstime desc limit 10'
return db.execute(sql, [phoneNo]);
My controller:
exports.getColumnChart = function(req, res) {
const phoneNo = req.body.userId
const userType = req.body.userType
console.log(phoneNo)
dashboardModule.getChartData(phoneNo, userType)
.then(([rows]) => {
if (rows.length > 0) {
console.log(rows)
return res.json(rows)
} else {
console.log("error")
return res.status(404).json({ error: 'Phone No. already taken' })
}
})
.catch((error) => {
console.log(error)
return res.status(404).json({ error: 'Something went wrong !!' })
})
}
I am sending this data to Ui and when I am receiving it on UI it is in the form of object inside array which is not the required data type I want
axios().post('/api/v1/Dashboard/DashboardColumnChart',this.form)
.then(res=>{
console.log(res.data)
debugger
this.chartData= res.data
})
The above code consoles on browser like
I am not getting any idea how o do it should I do it with backend or with front end and how
Nodejs will send you a JSON response if you want to change it. It is better to change or maniuplate it in a Front end framework. But if you want to change it in backend as you have asked Make sure that the rows is in the format that you want to recive.
let data = [
{ "name": "Dheeraj", "amount": "77.0000" },
{ "name": "Raju", "amount": "255.0000" }
]
// empty array to store the data
let testData = [];
data.forEach(element => {
testData.push(element.name)
});
You can format it using array.map and Object.values. map functions loops over each element and returns a modified element according to the callback provided. Object.values simply returns all the values of an object in an array.
const data = [ { "name": "Dheeraj", "amount": "77.0000" }, { "name": "Raju", "amount": "255.0000" } ];
const formattedData = data.map(obj => Object.values(obj));
console.log("Initial Data: ", data);
console.log("Formatted Data: ", formattedData);
// Map function example
const a = [1,2,3]
const mappedA = a.map(e => e * 2)
console.log(a, " mapped to: ", mappedA);
// Object.values example
const b = { firstName: 'John', lastName: 'Doe', number: '120120' }
console.log(Object.values(b));

Json string array to object in Vuex

In my states I have categories. In the categories array every each category have a settings column where I have saved json array string.
My question it is,how can I turn my string to object by filtering the response ?
My response:
[{"id":4,"name":"Vehicles","slug":"vehicles","settings":"[{"edit":true,"searchable":true}]","created_at":"2019-01-26 16:37:36","updated_at":"2019-01-26 16:37:36"},
This is my loading action for the categories:
const loadCategories = async ({ commit }, payload) => {
commit('SET_LOADING', true);
try {
const response = await axios.get(`admin/store/categories?page=${payload.page}`);
const checkErrors = checkResponse(response);
if (checkErrors) {
commit('SET_DIALOG_MESSAGE', checkErrors.message, { root: true });
} else {
commit('SET_STORE_CATEGORIES', response.data);
}
} catch (e) {
commit('SET_DIALOG_MESSAGE', 'errors.generic_error', { root: true });
} finally {
commit('SET_LOADING', false);
}
};
This is my SET_STORE_CATEGORIES:
const SET_STORE_CATEGORIES = (state, payload) => {
state.categories=payload.data;
state.pagination = {
currentPage: payload.current_page,
perPage: payload.per_page,
totalCategories: payload.total,
totalPages: payload.last_page,
};
};
Here I would like to add to modify the value ,to turn the string to object.
Had to add:
let parsed=[];
parsed=response.data.data.map((item)=>{
console.log(item);
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
response.data.data=parsed;
commit('SET_STORE_CATEGORIES', response.data);
You could map your response data as follows by parsing that string to an object :
let parsed=[];
parsed=response.data.map((item)=>{
let tmp=item;
tmp.settings=JSON.parse(item.settings);
return tmp;
});
commit('SET_STORE_CATEGORIES', parsed);

Why isn't my function returning the proper JSON data and how can I access it?

I'm running services to retrieve data from an API. Here is one of the services:
robotSummary(core_id, channel_name){
const params = new HttpParams()
var new_headers = {
'access-token': ' '
};
this.access_token = sessionStorage.getItem('access-token');
new_headers['access-token'] = this.access_token;
const myObject: any = {core_id : core_id, channel_name: channel_name};
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
const options = { params: new HttpParams(httpParams), headers: new_headers };
return this.http.get(this.baseURL + 'web_app/robot_summary/',options)
.subscribe(
res => console.log(res),
)
}
}
The data shows up properly on the console, but I still can't access the individual keys:
Here is how I call it:
ngOnInit(): void{
this.login.getData(this.username, this.password).subscribe((data) => {
this.robotSummaryData = this.getRobotSummary.robotSummary(this.core_id, this.channel_name);
console.log("robosummary"+ this.robotSummaryData)
});
}
When I call this function and assign it to a variable, it shows up on console as [object Object]. When I tried to use JSON.parse, it throws the error: type subscription is not assignable to parameter string. How can I access the data? I want to take the JSON object and save it as an Object with appropriate attributes. Thanks!
Do not subscribe inside your service, do subscribe in your component, change your service as follows,
robotSummary(core_id, channel_name){
const params = new HttpParams()
var new_headers = {
'access-token': ' '
};
this.access_token = sessionStorage.getItem('access-token');
new_headers['access-token'] = this.access_token; const myObject: any = { core_id: core_id, channel_name: channel_name };
const httpParams: HttpParamsOptions = { fromObject: myObject } as HttpParamsOptions;
const options = { params: new HttpParams(httpParams), headers: new_headers };
return this.http.get(this.baseURL + 'web_app/robot_summary/', options)
.map((response: Response) => response);
}
and then in your component,
ngOnInit(){
this.api..getRobotSummary.robotSummary(this.core_id, this.channel_name).subscribe((data) => {
this.data = data;
console.log(this.data);
});
}

Casting Response from HTTP Post to List of Typescript Objects

I have a call to my web API already written. The API returns a list of objects serialized in JSON. I know that there are fairly reasonable ways to cast individual items from JSON to typescript objects, but I cant figure out a way to do this casting to make it return a list of a typescript object.
I need to cast to a typescript object as there is a function in the object I want to be able to run, but without casting the function does not exist.
Here is the code used to retrieve the JSON:
findTrainPage(filter = '', sortOrder = 'desc', pageNumber = 0, pageSize = 15, departStart=null, departEnd=null, origStatusWhitelist=null): Observable<Train[]>
{
//retrieves a page of trains to display in the train list
let url = AppUtils.backendApiUrl() + '/trainList/getPage';
let requestBody = { 'filter': filter, 'sortOrder': sortOrder, 'pageNum': pageNumber, 'pageSize': pageSize, 'departStart': departStart, 'departEnd': departEnd, 'origStatusWhitelist': origStatusWhitelist };
let options = new RequestOptions({ headers: AppUtils.commonHttpHeaders() });
let headers = { headers: AppUtils.commonHttpHeaders() };
return this.http.post(url, requestBody, headers).map(res => res.json()).catch(error => Observable.throw(error.json()));
}
And here is the Train object I am trying to cast to:
export class Train implements TrainInterface
{
trainGUID: string;
trainSymbol: string;
createTime: string; //Should be formatted as a date, SQL table uses smalldatetime
departTime: string;
origStatus: OriginalStatuses;
badGUIDFlag: boolean;
trips: Trip[];
private _evalStatus: EvalStatuses;
get evalStatus(): EvalStatuses
{
return this.trips.reduce((min, p) => p.evalStatus < min ? p.evalStatus : min, this.trips[0].evalStatus);
}
}
I have looked at the following SO posts:
JSON to TypeScript class instance?
Angular2 HTTP GET - Cast response into full object
Create a response wrapper class. This should match with the API response structure.
export declare class ResponseWrapper<T> {
static SUCCESS: number;
data: Array<T>;
}
Then map the response as follows.
findTrainPage(filter = '', sortOrder = 'desc', pageNumber = 0, pageSize = 15, departStart = null, departEnd = null, origStatusWhitelist = null): Observable<any> {
//retrieves a page of trains to display in the train list
// let url = AppUtils.backendApiUrl() + '/trainList/getPage';
const url = 'assets/mockdata.json';
let requestBody = {
'filter': filter,
'sortOrder': sortOrder,
'pageNum': pageNumber,
'pageSize': pageSize,
'departStart': departStart,
'departEnd': departEnd,
'origStatusWhitelist': origStatusWhitelist
};
let options = new RequestOptions();
return this.http.get(url)
.map(res => res.json())
.catch(error => Observable.throw(error.json()));
}
Usage :
trainList : Train[];
constructor(private trainService: TrainService) {
this.trainService.findTrainPage()
.subscribe(data =>{
const resultsWrapper:ResponseWrapper<Train> = data;
this.trainList = resultsWrapper.data;
});
// error => this.errorMessage = error);
}
Here is the tested source https://gitlab.com/supun/angular-stack-overflow-ref

Typescript converting a JSON object to Typescript class

Hello I am attempting to change an array of JSON objects to a TypeScript class. However the method seems to crash every I attempt to assign a Json object attribute to a typescript attribute.
Typescript interface
export interface marker {
lat: number;
lng: number;
}
Typescript method
public markers: marker[];
ngOnInit() {
this.mapService.GetPhotosById(this.id).subscribe(resultlisting => {
this.values = resultlisting;
console.log(this.values); //SHOW IN PICTURE
this.ChangetoMarkers(this.values);
}, error => this.errorMessage = error);
}
ChangetoMarkers(someArray: Observable<any[]>) {
for (let entry of someArray) {
let mark: marker;
mark.lat = Number(entry.latitude); //Attempt to convert to number
mark.lng = +entry.longitude; //2nd attempt to convert to number
this.markers.push(mark);
};
console.log(this.markers); //DOES NOT REACH THIS
}
Map Service
GetPhotosById(id: string): Observable<any> {
return this.http
.post(this.config.apiEndpoint + "mapPhotos/" + id)
.map(this.extractJson).catch(this.handleErrors);
};
private extractJson(res: Response) {
let data = res.json();
return data;
}
private handleErrors(error: Response | any) {
let errMsg: string;
if (error instanceof Response) {
const body = error.json() || '';
const err = body.error || JSON.stringify(body);
errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
} else {
errMsg = error.message ? error.message : error.toString();
}
console.log(errMsg);
return Observable.throw(errMsg);
}
I have researched the issue and have attempted to apply the interger cast but it does not seem to work. Any suggestions would be great.
As  Mauricio Poppe noted in his comment, you are trying to access the properties of a variable that has no value.
changeToMarkers(points: Array<{latitude: number, longitude: number}>) {
this.markers = entries.map(({latitude: lat, longitude: lng}) => ({
lat,
lng
}));
console.log(this.markers);
}
No number conversions are necessary because the deserialized representations of latitude and longitude are already compatible numeric values.
Try this:
ChangetoMarkers(someArray: any[]) {
console.log("array",someArray);
for (let entry of someArray) {
let mark: marker = {lat: entry.latitude, lng: entry.longitude};
console.log("mark", mark);
this.markers.push(mark);
};
console.log("markers",this.markers);
}
It isn't as elegant as Aluan Haddad's, but it should allow you to determine at which point it is breaking if for some reason this still doesn't work, by logging someArray before the loop, the marks before being pushed, and this.markers after to determine exactly where the problem is breaking down.