Hi I am trying to format my graphql query to json request like this. I want to pass id as string with value "3", RN when I am sending this as a json request , graphql denies with error. How do I resolve this ?
{"query":"{user(id:3){id,firstName,age}}"} {
"errors": [
{
"message": "String cannot represent a non string value: 3",
"locations": [
{
"line": 1,
"column": 10
}
]
}
]
}
Added schema in edit1:
`# Exposes a URL that specifies the behavior of this scalar.
directive #specifiedBy(
The URL that specifies the behavior of this scalar.
url: String!
) on
| SCALAR
schema {
query: RootQueryType
mutation: Mutation
}
type Company {
id: String
name: String
description: String
users: [User]
}
type Mutation {
addUser(firstName: String!, lastName: String, age: Int!, socialSecurity: String, companyId: String): User
deleteUser(id: String!, companyId: String): User
editUser(id: String!, firstName: String, lastName: String, age: Int, socialSecurity: String, companyId: String): User
addCompanies(name: String!, description: String): Company
editCompanies(id: String!, name: String, description: String): Company
}
type RootQueryType {
user(id: String): User
company(id: String): Company
}
type User {
id: String
firstName: String
lastName: String
age: Int
socialSecurity: String
company: Company
}
`
Without having the schema it is a bit hard to be sure, but it seems like you need to change the type of the input id of the user field from String to ID. The scalar ID type does accept strings and numbers as input.
Related
I would like to create an instance of the Customer class from Json object.
But using the plainToInstance function of class-transformer I don't have the proper class instance as a type save typescript object.
What I'm doing bad?
Import
import { plainToInstance } from 'class-transformer';
Customer JSON
const json = `{
"id": "1",
"name": "Jogn",
"surname": "Doe",
"email": "j.doe.test#gmail.com",
"phone": "123456789"
}
}
`;
Customer class definition
import { Field, ObjectType, Directive, ID } from '#nestjs/graphql';
import { Address } from './address';
#ObjectType()
#Directive('#key(fields: "id")')
export class Customer {
#Field(() => ID)
id: string;
#Field()
name: String;
#Field({nullable: true})
surname?: String;
#Field()
email: String;
#Field({nullable: true})
phone?: String;
#Field()
customerType: String;
#Field()
customerStatus: String;
#Field(() => [Address], { nullable: true })
addresses?: [Address]
}
Transformation from Json to Customer instance
let customer : Customer = plainToInstance(Customer, json) as Customer;
console.log('customer.email);
Console result
Customer email: undefined
So I couldn't get the email of the customer here
This is what I have when I log the entire customer variable
console.log(customer);
{
"id": "1",
"name": "Jogn",
"surname": "Doe",
"email": "j.doe.test#gmail.com",
"phone": "123456789"
}
Test with creating the Customer instance inline
var x = new Customer();
x.id = "123";
console.log(x)
So, now the object looks properly in the console
Customer { id: '123' }
You must pass a json object to plainToInstance - not a string.
i.e. your json variable should be
const json = {
id: '1',
name: 'Jogn',
surname: 'Doe',
email: 'j.doe.test#gmail.com',
phone: '123456789',
};
here's a working Stackblitz example
The second attribute of plainToInstance should be a plain object so you have to parse your json string into an object:
let customer = plainToInstance(Customer, JSON.parse(json))
Here is my json file
{
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": m,
"data": { "age": 26, "born": "UK" }
},
]
}
This data array could have more entries.
I have to map the values into an interface which looks like:
InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
I am unable to change the interface. So I'm trying to do some pseudo coding.
const list;
list = convertToInterfacePerson = (value): Array<InterfacePerson> => {
return {
id: value.id,
title: if(value.gender === "m")? "Mr" : "Mrs",
firstName: value.firstName,
lastName: value.lastName,
age: value.data.age,
//...
}
}
I think you were trying to use a conversion mapping function called convertToInterfacePerson but you hadn't set it up yet (separately from trying to use it). The code below shows it declared and used within a map Array method call. I believe this resolves the error(s) you were getting.
// Copied in the JSON for demonstration
const sourceJson = {
"data": [
{
"firstName": "Tom",
"lastName": "Yoda",
"type": "guest",
"id": "0",
"gender": "m",
"data": { "age": 26, "born": "UK" }
},
]
};
// Declared the InterfacePerson interface
interface InterfacePerson {
id: string;
title: string;
firstName: string;
lastName: string;
age: string;
location: string;
}
// Declared the conversion mapping function (optional parameter typing included)
const convertToInterfacePerson = (value: { firstName: string, lastName: string, type: string, id: string, gender: string, data: { age: number, born: string } }): InterfacePerson => {
return {
id: value.id,
// Removed the `if` statement due to ternary conditional
title: ((value.gender === "m") ? "Mr" : "Mrs"),
firstName: value.firstName,
lastName: value.lastName,
// Wrapped the value.data.age in a string conversion
age: String(value.data.age),
location: value.data.born
};
}
// Declared and assigned the list based on the returned array from the mapping function (each element is applied in the `convertToInterfacePerson` function)
const list = sourceJson.data.map(convertToInterfacePerson);
// Show the result of the conversion
console.log(JSON.stringify(list, null, 2));
And for a live example, check out this TypeScript Playground script containing this solution.
I try to Post Json with alamofire, which I can, but I need a value that I get from the result of that successful API post. how do I get value from post method JSON in swift? i use Alamofire to make things simple.
{
"phoneNum": "+1234566869",
"phoneNumTarget": "+2345687960",
"id": "79999000"
}
so this is the body parameter for my Post JSON,
and this is the result of a successful post JSON
{
"data": {
"orderId": "79999000",
"uniquesRoomId": 12341414,
"users": [
{
"avatar_url": "https:// some web",
"phone_number": "085858490282",
"fullname": "BuzzLightyear"
},
{
"avatar_url": "https:// some web",
"phone_number": "085858490282",
"fullname": "General Zurg"
}
],
"chat_name": "user2"
},
"message": "room has been successfully created",
"success": true
}
Now I want to retrieve all the value that I get from that post Json method, how do I do it? do I need to make a struct first like when I want to make get method request for JSON?
*update question
let data : [DataClass] = [ ]
AF.request(web, method: .post, parameters: chataja,encoder:
JSONParameterEncoder.default).responseJSON { (response) in
switch (response.result) {
case.success :
self.data = response
break
i try for this and it getting some error
You need to parse this response through Decodable confirmed structs
import Foundation
// MARK: - User
struct User: Codable {
let data: DataClass
let message: String
let success: Bool
}
// MARK: - DataClass
struct DataClass: Codable {
let orderID: String
let uniquesRoomID: Int
let users: [UserElement]
let chatName: String
enum CodingKeys: String, CodingKey {
case orderID = "orderId"
case uniquesRoomID = "uniquesRoomId"
case users
case chatName = "chat_name"
}
}
// MARK: - UserElement
struct UserElement: Codable {
let avatarURL: String
let phoneNumber, fullname: String
enum CodingKeys: String, CodingKey {
case avatarURL = "avatar_url"
case phoneNumber = "phone_number"
case fullname
}
}
AF.request(web, method: .post, parameters: chataja,encoder:
JSONParameterEncoder.default).responseJSON { (response) in
switch (response.result) {
case .success(let data) :
let user = try? JSONDecoder().decode(User.self, from: data)
I am using Retrofit to call API and using converter-gson to convert response json to kotlin
This is response
{
"id": "1",
"rank": "1",
"name": "Challenge",
"status": "E",
"createDate": "2018-09-17 15:01:28",
"lastModDate": "2018-09-17 15:06:32",
"category": "DINING",
"photo": {
"path": "http://example.com/xxx.jpg",
"size": [
400,
267
]
}
}
And this is data class.
data class ServiceList (val id:Int,
val rank:Int,
val name:String,
val status:String,
val lastModDate:String,
val category:String,
???????)
How to complete this class?
You can declare another data class to describe the photo property like so:
data class ServiceList(val id: Int,
val rank: Int,
val name: String,
val status: String,
val lastModDate: String,
val category: String,
val photo: Photo) {
data class Photo(val size: List<Int>, val path: String)
}
If the Photo is to be used in other contexts as well you can pull it out to be a top level class:
data class ServiceList (val id: Int,
val rank: Int,
val name: String,
val status: String,
val lastModDate: String,
val category: String,
val photo: ServiceListPhoto)
data class ServiceListPhoto(val size: List<Int>, val path: String)
I have some data I'll be fetching at runtime:
/* {id: 1, name: 'brad', age: 27, address: { city: 'city1', state: 'state1' } } */
let data = "{\"id\":1,\"name\":\"brad\",\"age\":27,\"address\":{\"city\":\"city1\",\"state\":\"state1\"}}";
Using ReasonML and BuckleScript, how can I can get this data in the form:
type address = {
city: string,
state: string
};
type person = {
id: int,
name: string,
age: option int,
address: option address
};
The solution I've come up with are 100s of lines long.
Using bs-json:
let parseAddress json =>
Json.Decode.{
city: json |> field "city" string,
state: json |> field "state" string
};
let parsePerson json =>
Json.Decode.{
id: json |> field "id" int,
name: json |> field "name" string,
age: json |> optional (field "age" int),
address: json |> optional (field "address" parseAddress)
};