• Apollo GraphQL

    Level Up Tutorials | Web Development & Design Tutorials

    Snippets

    GraphQL type:

    type Feed {
        _id: String!
        name: String!
        description: String
        ownerId: String!
        posts: [Post]
        isOwner: Boolean
        isActiveSubscription: Boolean
        isPendingSubscription: Boolean
    }
     

    Mutations and queries:

    type Mutation {
        createFeed(name: String!, description: String): Feed
        deleteFeed(id: String!): Boolean
    }
     
    type Query {
        feedById(_id: String!): Feed
        feedByInviteCode(inviteCode: String!): Feed
        feeds: [Feed]
        subscriptions: [Feed]
    }
     

    Resolvers:

    Query: {
          async feedById(_: any, { _id }: any, __: any) {
            return Feeds.findOne(_id)
          },
    },
    ,
    Mutation: {
    	async createFeed(_: any, { name, description }: any, context: any) {
    		const user = await context.user()
    		const id = Feeds.insert({
    			name: name,
    			description: description,
    			ownerId: user._id,
    			createdAt: new Date(),
    			posts: [],
    			inviteCode: Random.id()
    		})
     
    		return Feeds.findOne(id)
    	}
    }
     

    Usage:

    const GET_FEED = gql`
        query feedById($id: String!) {
            feedById(_id: $id) {
                _id
                name
                ownerId
                isOwner
                isActiveSubscription
                posts {
                    _id
                    text
                    poster {
                        _id
                        email
                    }
                    media {
                        _id
                        publicId
                    }
                }
            }
        }
    `
     
    const { data, loading } = useQuery(GET_FEED, {
    	variables: {
    		id: feedId
    	}
    })
     

Typescript “builder” pattern

export interface Person {
	name: string
	dateOfBirth: string
	age: number
}
 
export const buildPerson = (overrides: Partial<Person> = {}): Person => ({
	name: "Some default",
	dateOfBirth: "Some default date",
	age: 25,
	...overrides,
})