http getJSON in Nativescript - nativescript

I downloaded the News Feed with Images and Text Items Nativescript app locally and am trying to make it work with a live feed from newsapi.org.
The original app has json hardcoded like so:
allNews: { source: Source, author: string, title: string, description: string, url: string, urlToImage: string, publishedAt: string }[] = [{ "source": { "id": null, "name": "Yahoo.com" }, "author": null, "title": "The Latest: Russia says no evidence of gas attack in Douma", "description": null, "url": "https://www.yahoo.com/news/latest-turkey-urges-sides-avoid-more-syria-turmoil-113652213.html", "urlToImage": null, "publishedAt": "2018-04-13T19:44:00Z" }, { "source": { "id": "the-washington-post", "name": "The Washington Post" }, "author": "http://www.facebook.com/matt.zapotosky", "title": "Trump issues pardon to 'Scooter' Libby, former chief of staff to Vice President Cheney", "description": "The Bush administration aide was convicted of perjury before a grand jury, lying to FBI investigators and obstruction of justice.", "url": "https://www.washingtonpost.com/politics/trump-issues-pardon-to-scooter-libby-former-chief-of-staff-to-vice-president-cheney/2018/04/13/dfa4039a-3f2d-11e8-8d53-eba0ed2371cc_story.html", "urlToImage": "https://www.washingtonpost.com/rf/image_1484w/2010-2019/WashingtonPost/2018/04/13/National-Politics/Images/AFP_13Z4QQ.jpg?t=20170517", "publishedAt": "2018-04-13T19:06:25Z" }, { "source": { "id": "the-new-york-times", "name": "The New York Times" }, "author": "", "title": "Where's the Boom in Bank Lending?: DealBook Briefing", "description": "Bank lending was expected to surge this year. But going by bank results so far, lending in the first quarter is set to disappoint.", "url": "https://www.nytimes.com/2018/04/13/business/dealbook/trump-trans-pacific-partnership.html", "urlToImage": "https://static01.nyt.com/images/2018/02/03/us/14db-newsletter-wells/14db-newsletter-wells-facebookJumbo-v2.jpg", "publishedAt": "2018-04-13T18:56:00Z" }];
Inside my app/home/home-view-model.ts I added:
import { getJSON } from "tns-core-modules/http";
...
allNews: { source: Source,
author: string,
title: string,
description: string,
url: string,
urlToImage: string,
publishedAt: string
}[] = getJSON("newsapi link").then((r: any) => {
}, (e) => {
});
;
I am doing this based on the documentation here: https://docs.nativescript.org/ns-framework-modules/http. However, getting an error:
app/home/home-view-model.ts(20,5): error TS2322: Type 'Promise<void>' is not assignable to type '{ source: Source; author: string; title: string; description: string; url: string; urlToImage: string; publishedAt: string; }[]'.
Property 'length' is missing in type 'Promise<void>'.
app/home/home-page.ts(1,27): error TS2307: Cannot find module 'data/observable'.
app/home/home-page.ts(2,29): error TS2307: Cannot find module 'ui/layouts/stack-layout'.
app/home/home-view-model.ts(20,5): error TS2322: Type 'Promise<void>' is not assignable to type '{ source: Source; author: string; title: string; description: string; url: string; urlToImage: string; publishedAt: string; }[]'.
Property 'length' is missing in type 'Promise<void>'.
Any help appreciated!

You're assigning the result of the .then call, which is a Promise. Both the call to getJSON() and .then() return promises (to allow chaining).
Instead, you want to assign the value inside the resolve handler of the promise:
allNews: { source: Source,
author: string,
title: string,
description: string,
url: string,
urlToImage: string,
publishedAt: string
}[]; // just declare the variable here
getJSON("newsapi link").then((r: any) => {
allNews = r; // assign it from the response when successful
}, (e) => {
});
Here's a link with more information on Promises that might be helpful:
https://www.datchley.name/es6-promises/

I wanted to be sure and follow up with a complete solution here. I needed to assign the getJSON function to a variable to get this to work. Note the fooBar variable below:
allNews: { source: Source,
author: string,
title: string,
description: string,
url: string,
urlToImage: string,
publishedAt: string
}[]; // just declare the variable here
getData = getJSON("newsapi link").then((r: any) => {
this.allNews = r; // assign it from the response when successful
}, (e) => {
});

Related

Input type in apollo graphql isnt working properly

I am using apollo graphql and for creating new data a want to use input type data.
I found documentation about this https://www.apollographql.com/docs/apollo-server/schema/schema/#input-types but there is nowhere about how to call it from resolvers.
This is my code:
const { ApolloServer, gql } = require('apollo-server');
var typeDefs=gql`
input CourseInput {
id: Int
title: String
author: String
description: String
topic: String
url: String
}
type Course {
id: Int
title: String
author: String
description:String
topic:String
url: String
}
type Mutation {
createCourse(input: CourseInput): [Course]
}
`;
var coursesData = [
{
id: 1,
title: 'First one',
author: 'Andrew Mead, Rob Percival',
description: 'Learn Node.js',
topic: 'Node.js',
url: 'https://example.com'
},
{
id: 2,
title: 'Node.js, Express & MongoDB Dev to Deployment',
author: 'Brad Traversy',
description: 'Learn by example building & deploying reah',
topic: 'Node.js',
url: 'https://newbook.com'
},
]
var resolvers= {
Mutation: {
createCourse:(parent,{input})=>{
coursesData = [...coursesData, input];
console.log("input je" ,input)
console.log("coursesdata" ,coursesData)
return coursesData;
}
},
};
const server = new ApolloServer({ typeDefs, resolvers,tracing:true });
// The `listen` method launches a web server.
server.listen().then(({ url }) => {
console.log(`🚀 Server ready at ${url}`);
On my localhost:4000 I am making query to create new course like this:
mutation createCourse($input: CourseInput) {
createCourse(input: $input) {
id
title
author
description
topic
url
}
}
{
"input": {
"id": 4,
"title": "ovo je novi kurs",
"author": "delila",
"description": "neki novi description",
"topic": "programming",
"url": "google.com"
}
}
But result of adding new course is always null. I think there is problem with resolver but even I did research I couldn't find the solution. If someone knows where is problem please post answer and help me!
You can look at image
Thank you

How to pass nested variables to the GraphQL query in Apollo?

Trying to pass nested variables to the GraphQL query but my server gets only top-level variables (shopId), everything else is null.
I tried:
#1
const CALCULATE_PACKAGE_PRICE = gql`
query CalculatePackagePrice(
$shopId: String!
$address1: String
$zip: String
$city: String
$countryCode: String
) {
calculatePackagePrice(
where: {
shopId: $shopId
destination: {
address1: $address1
zip: $zip
city: $city
countryCode: $countryCode
}
}
) {
name
price
userErrors {
field
message
}
}
}
`
const [calculatePackagePrice, { loading, data }] = useLazyQuery(
CALCULATE_PACKAGE_PRICE,
{
variables: {
shopId: shopId,
destination: {
address1: "Example 123",
zip: "123",
city: "Test",
countryCode: "US",
},
},
}
)
And #2:
export function CALCULATE_PACKAGE_PRICE({ shopId, destination }) {
return gql`
query CalculatePackagePrice {
calculatePackagePrice(
where: {
shopId: "${shopId}"
destination: {
address1: "${destination.address1}"
zip: "${destination.zip}
city: "${destination.city}"
countryCode: "${destination.countryCode}"
}
}
) {
name
price
userErrors {
field
message
}
}
}
`
}
const [calculatePackagePrice, { loading, data }] = useLazyQuery(
CALCULATE_PACKAGE_PRICE({
shopId: shopId,
destination: {
address1: "Example 123",
zip: "123",
city: "Test",
countryCode: "US",
},
})
)
It works just fine when I hardcoded variables content to the queries. What I'm doing wrong?
Here is a helpful snippet from graphql docs,
All declared variables must be either scalars, enums, or input object types. So if you want to pass a complex object into a field, you need to know what input type that matches on the server.
You're correctly passing in the variables as strings, but then trying (perhaps successfully, but I've never seen the syntax before) to create the object in the gql template string. Instead, create an input type for destination and where.
input WhereInput {
shopId: String!
destination: DestinationInput!
}
input DestinationInput {
address1: String!
zip: String!
city: String!
countryCode: String!
}
then change the query on the client (and update the server definition),
const CALCULATE_PACKAGE_PRICE = gql`
query CalculatePackagePrice($where: WhereInput!) {
calculatePackagePrice(where: $where) {
name
price
userErrors {
field
message
}
}
}
`
then pass the variables like,
const [calculatePackagePrice, { loading, data }] = useLazyQuery(
CALCULATE_PACKAGE_PRICE,
{
variables: {
where: {
shopId,
destination: {
address1: "Example 123",
zip: "123",
city: "Test",
countryCode: "US",
},
},
}
}
)

Graphql Schema (Apollo) nested object

I have an API endpoint that returns the following data:
{
"2017": {
"May": [
{},
{}
],
"June": []
},
"2018": {}
}
How can I create a schema for those nested objects as it seems I cannot create nested objects in the schema.
I am using the typeDefinitions with graphql-tools which works well for objects and arrays of objects but I could not find a way to tackle this.
a typical type looks like:
type Venue {
name: String,
url: String,
streetAddress: String,
streetAddress2: String,
streetAddress3: String,
city: String,
postalCode: String,
country: String,
phoneNumber: String,
info: String
}
and can be used in another type as follow:
type Event {
title: String,
subTitle: String,
slug: String,
venues: [Venue],
...
}
but I cannot do something like:
type Calendar {
year: {
month: [Event]
}
}
try to separate the nested objects:
type Year {
month: [Event]
}
type Calendar {
year: Year
}

Why mongo crop an array before save?

I try to save the object to a collection of mongoDb.
The object contents array of objects (name 'Children'). If the Children array length more than 20, mongo returns me empty Children array (it contents only one object with mongo's _id property).
How can I determine where is the error?
var object = {
"BrowseNodeId": "2619526011",
"Name": "Appliances",
"IsCategoryRoot": "1",
"Children": [{
"BrowseNodeId": "3737671",
"Name": "Air Conditioners"
},
// Here 30 objects {}
],
"Ancestors": {
"BrowseNodeId": "2619525011",
"Name": "Appliances"
},
};
I use $.ajax to make a post query:
$.ajax({
url: 'http://localhost:8005/api/category',
data: object,
method: 'POST',
dataType: 'application/json'
}).done((res) => {
console.log(res);
// => returns object with Children.length == 1
})
But If I use the Postman to make a post query - object comes to me with Children array length as I expect == 20.
Mongoose schema:
mongoose.model('category', new mongoose.Schema(
{
BrowseNodeId: Number,
Name: String,
Children: [{
BrowseNodeId: Number,
Name: String,
}],
Ancestors: {
BrowseNodeId: Number,
Name: String,
},
level: Number,
}
))
The implementation of http://localhost:8005/api/category:
var koa = require('koa');
var router = require('koa-router')();
var koaRestMongoose = require('koa-rest-mongoose');
var cors = require('koa-cors');
var mongoUrl = '127.0.0.1:27017/dbname';
var mongoose = require('mongoose');
mongoose.connect(mongoUrl);
var model = {
category: mongoose.model('category', new mongoose.Schema(
{
BrowseNodeId: Number,
Name: String,
Children: [{
BrowseNodeId: Number,
Name: String,
}],
Ancestors: {
BrowseNodeId: Number,
Name: String,
},
level: Number,
}
)),
item: mongoose.model('item', new mongoose.Schema(
{
BrowseNodeId: Number,
Name: String,
}
)),
}
var app = koa();
app.use(cors());
koaRestMongoose(app, router, model.category, '/api');
koaRestMongoose(app, router, model.item, '/api');
app.use(router.routes());
app.listen(8005);
I assume it may be schema issue
UPD
When I use ajax request body is:
Cat: { Name: 'Test',
'Children[0][BrowseNodeId]': '11',
'Children[1][BrowseNodeId]': '11' }
With the Postman request is:
Children: [ { BrowseNodeId: '11' }, { BrowseNodeId: '11' } ] }

How to mutate nested object using graphql

I have a mongoose schema like the one below:
import mongoose from 'mongoose'
const ProjectSchema = new mongoose.Schema({
name: {
type: String
},
owner: {
type: String
},
member: {
type: String
},
updatedDate: {
type: Date
},
description: {
type: String
},
folder: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Folder'
},
dataSources: [{
name: {
type: String
},
updatedDate: {
type: Date
},
}],
propjectHistory: [{
no: {
type: Number
},
member: { // is this reference or just a string?
type: String
},
action: {
type: String
},
updatedDate: {
type: Date
},
}]
})
const Project = mongoose.model('Project', ProjectSchema)
And I integrated with graphql using graffiti and graffiti-mongoose.
However, the Graphiql documentation shows that I only have the ones below:
addProject(input: addProjectInput!):
name: String
owner: String
member: String
updatedDate: Date
description: String
folder: ID
clientMutationId: String!
I could successfully add project with a mutation query only using those parameters, but it seems that I cannot even send mutation query with projectHistory and dataSource, which are embedded inside project schema.
However, I can access projectHistory and dataSource when I send find queries.
I can't find any documentation about the problem.
sample mutation query without nested ones works.
mutation {
addProject(input:{
clientMutationId: "1"
name: "testproject",
owner: "keonwoo",
member: "keonwoo",
updatedDate: "2015-07-24T13:23:15.580Z",
description: "this is test project",
folder: "56fb93403eab9e1c14358fb7"
}){
clientMutationId
changedProjectEdge{
node{
_id
name
updatedDate
}
}
}
}
the above mutation returns the following:
{
"data": {
"addProject": {
"clientMutationId": "1",
"changedProjectEdge": {
"node": {
"_id": "56fb93ab3eab9e1c14358fb8",
"name": "testproject",
"updatedDate": "2015-07-24T13:23:15.580Z"
}
}
}
}
}
I am not using client like relay.
the problem was with the graffiti-mongoose library.
Turns out that maintainers of graffiti-mongoose just added embedded object feature and I did not update.

Resources