I'd like to retrieve the _id of a document in my mongodb database using a graphql query.
Here is my query:
query {
getTeamRegistrationID(teamName:"Patriots") {
_id
}
}
And the result:
{
"data": {
"getTeamRegistrationID": []
}
}
This should return the ObjectID of the document from the mongodb database.
Here's my graphql schema:
const typeDefs = gql`
type TeamRegistration {
_id: ID,
teamName: String
},
type Query {
getTeamRegistrationID(teamName: String): [TeamRegistration]
}`
My resolver:
const resolvers = {
Query: {
getTeamRegistrationID: (parent, teamRegistration) => TeamRegistration.find({ teamName: teamRegistration.teamName })
}
}
I can't figure out what I'm doing wrong here. Is there something I'm missing? Thanks in advance!
Related
A lot of this is very new to me since I have been a PHP developer for so long.
I am having a couple of issues that I know are easy to fix. I just have limited experience and am learning.
I cannot seem to pass the argument $token_id. I am using next JS, and I just want to take the number on the [id].js page, and pass it as the token ID.
I can't seem to get data from traitType, which is an object named "traits" which has an array of objects inside of it.
export async function getStaticProps(context) {
const client = new ApolloClient({
uri: 'http://localhost:3000/api/graphql',
cache: new InMemoryCache()
});
const token_id = String(context.params.id)
const { data } = await client.query({
query: gql`
query myQuery($token_id: String!) {
getData(token_id: $token_id) {
token_id
name
}
}
`
},{ variables: { token_id } });
props: {
data: data,
}
}
export async function getStaticPaths() {
return {
paths: [], //indicates that no page needs be created at build time
fallback: 'blocking' //indicates the type of fallback
}
}
My Type Definition
type Blah {
token_id: String
name: String
#traits: [traitType] #TODO: returns nothing since data is array
}
type traitType {
trait_type: String
value: String
}
I have to hard code the token
getData(token_id: "6") {
token_id
name
traits {
trait_type
}
}
I have tried several variations in the graphql query
query getDataQuery($token_id: String! = "6") {
getData(token_id: $token_id) {
Returns Null on traits, and $token id is null, and nothing is found
"traits": [
{
"trait_type": null,
"value": null
}
],
And my JSON from mongo db is an array with an object.
"traits" : [
{
"trait_type" : "birthday",
"value" : 1627423029.0,
}
]
I can post more than just fragments of code. Sorry for the formatting.
RedwoodJS automatically maps GraphQL queries resolvers to api/src/services. How do I create a field resolver for a given GraphQL type?
Suppose I have this schema:
type Person {
name: string!
birthDate: DateTime!
age: Int!
}
But only name and birthDate are stored in the database.
Using graphql-tools I would write my resolvers like this:
const resolvers = {
Query: { ... },
Mutation: { ... },
Person: {
age(person) {
return new Date().getFullYear() - person.birthDate.getFullYear();
},
},
};
PS: I know the age formula is wrong.
PS2: I'm using age here for the sake of simplicity, imagine this is expensive to compute or get from database.
It's almost identical to the way you do it with graphql-tools.
You export an object with the same name as your type in your service:
// services/person.js
export const Person = {
age: (_args, { root }) {
return new Date().getFullYear() - root.birthDate.getFullYear();
},
}
As an aside, you could also export a resolvers in the person.sdl.js file (But services take precendence):
// graphql/person.sdl.js
export const schema = gql`/* ... */`
export const resolvers = {
Query: {},
Mutation: {},
Person: {},
}
Edit: I misunderstood the question, this answer just covers creating query + mutation resolvers, not a resolver for a computed field.
To create a field resolver, you'll need to decide whether you're creating a resolver for a query, or a handler for a mutation.
We can use the following schema as an example:
export const schema = gql`
type Person {
id: String!
name: String!
age: Int!
}
type PersonInput {
name: String
age: Int
}
type Mutation {
createPerson(input: PersonInput!): Person
}
type Query {
people: [Person]
person(id: String!): Person
}
`
If the above schema is stored in a file called persons.sdl.js, in the api/src/graphql directory, you can implement the queries and mutations in a file called persons.js in the api/src/services/persons directory.
// implements Mutation.createPerson(...)
export const createPerson({ input }) => {
return db.person.create({
data: input
})
}
// implements Query.people
export const people = () => {
return db.person.findMany()
}
// implements Query.person(...)
export const person = ({ id }) => {
return db.person.findOne({
where: { id }
})
}
Doing nightlife app on freecodecamp https://learn.freecodecamp.org/coding-interview-prep/take-home-projects/build-a-nightlife-coordination-app/
I am trying to implement 'Go' button, similarly 'Like' button on Youtube or Instagram. Users click the button the number(counting how many users go) goes up meaning users will go there and click again, it revokes, the number decreases, users will not go there.
It seems like working well except the issue, I have to refresh the page and then, the number has increased or decreased and throws the error like below so:
Invariant Violation: Can't find field getBars({}) on object {
"getBars({\"location\":\"vancouver\"})": [
{
"type": "id",
"generated": false,
"id": "Bar:uNgTjA9ADe_6LWby20Af8g",
"typename": "Bar"
},
{
"type": "id",
"generated": false,
"id": "Bar:CwL5jwXhImT_7K5IB7mOvA",
"typename": "Bar"
},
{
"type": "id",
"generated": false,
"id": "Bar:mdt1tLbkZcOS2CsEbVF9Xg",
"typename": "Bar"
},
.
.
.
I am assuming handling update function will fix this issue but unlike the example from Apollo documentation:
// GET_TODOS is not dynamic query
// nothing to pass as variables to fetch TODO list
<Mutation
mutation={ADD_TODO}
update={(cache, { data: { addTodo } }) => {
const { todos } = cache.readQuery({ query: GET_TODOS });
cache.writeQuery({
query: GET_TODOS,
data: { todos: todos.concat([addTodo]) },
});
}}
>
My query is dynamic:
// I have to pass location variable, otherwise it won't fetch anything.
const GET_BARS_QUERY = gql`
query getBars($location: String!) {
getBars(location: $location) {
id
name
url
rating
price
image_url
goings {
username
}
goingCount
}
}
`;
I believe I might need to handle to provide location using readQuery and writeQury but not too sure what I should do.
Here's my code:
const GoButton = ({ user, bar }) => {
const { token } = user;
const { id, goings, goingCount } = bar;
const [userGoes] = useMutation(GO_MUTATION, {
variables: { yelp_id: id },
update(proxy, result) {
const data = proxy.readQuery({
query: GET_BARS_QUERY
});
data.getBars = [result.userGoes, ...data.getBars];
proxy.writeQuery({ query: GET_BARS_QUERY, data });
}
});
return (
<Button onClick={userGoes}>
Go {goingCount}
</Button>
);
};
const GO_MUTATION = gql`
mutation go($yelp_id: String!) {
go(yelp_id: $yelp_id) {
id
goings {
id
username
}
goingCount
}
}
`;
export default GoButton;
Full code here https://github.com/footlessbird/Nightlife-Coordination-App
when you read/write the getBars query, you need to pass the location as a variable
const [userGoes] = useMutation(GO_MUTATION, {
variables: { yelp_id: id },
update(proxy, result) {
const data = proxy.readQuery({
query: GET_BARS_QUERY,
variables: {
location: 'New York'
}
});
data.getBars = [result.userGoes, ...data.getBars];
proxy.writeQuery({ query: GET_BARS_QUERY, data,
variables: {
location: 'New York'
}
});
}
});
My query for a single post shows
Cannot return null for non-nullable field Post.author
error message when I include the author field, both from React as well as the Playground. It's working fine for the posts query which queries for multiple posts and is able to retrieve the specific author, but not when I perform a single post query.
Client-side schema:
posts(query: String, first: Int, skip: Int, after: String, orderBy: UserOrderByInput): [Post!]!
post(id: ID): Post!
Query from React:
(gql is the same for post and posts except for the sorting arguments)
const { data, error, loading } = useQuery(GET_POST, {
variables: {
id: props.match.params.id
}
})
export const GET_POST = gql`
query Post($id: ID!) {
post(
id: $id
){
id
title
body
location
author{
id
firstName
lastName
}
}
}
`
Server-side query:
post(parent, args, { prisma }, info) {
if(!args.id) {
throw new Error("No search query input")
}
return prisma.query.post({
where: {
id: args.id
}, info})
},
I am trying to use graphql for one of the GET request based on an id. Here's the code:
const { graphql, buildSchema } = require('graphql');
EmployeeService.prototype.getEmployee = function() {
// Construct a schema
const schema = buildSchema(`
type Query {
employee(id="12345") {
id
items {
id
name
}
}
}
`);
// The root provides a resolver function
let root = {
employee: () => id
};
// Run the GraphQL query
graphql(schema, '{ employee }', root).then((response) => {
console.log(response);
});
};
Trying to follow the documentation on http://graphql.org/graphql-js/.
I get a GraphQL error: "Syntax Error GraphQL request (3:19) Expected :, found =↵↵2: type Query {↵3: employee (id="12345") {↵ ^↵4: id↵"
Please advise.
You are maybe mixing things a little bit up. The schema and resolvers are part of your API and are not needed to make a query on a client. Just for demonstration purposes here a valid schema definition (that would normally run on a API server):
let schema = buildSchema(`
type Item {
id: Int!
name: String!
}
type Employee {
id: Int!
items: [Item]
}
type Query {
employee(id: Int!): Employee
}
`);
You then define your types and resolvers (simplified examples):
class Employee {
constructor(id, items) {
this.id = id;
this.items = items;
}
}
let root = {
employee: ({id}) => {
return new Employee(id, [{id: 1, name: 'Item 1'}, {id: 2, name: 'Item2'}]);
}
};
You can then run a query:
const query = `
{
employee(id: 1) {
id,
items {
id,
name
}
}
}
`;
graphql(schema, query, root).then((response) => {
console.log(response.data);
});
To run actual queries against a remote API have a look at GraphQL clients like Apollo or lokka