Module 7 Summary
This lesson is a summary of the work we've done in Module 7.0.
π This module's quiz can be found - here.
ποΈ Solutions for this module's quiz can be found - here.
In this module, we had the client be able to request and present information for a certain listing in the /listing/:id
route of our application.
Server Project#
src/graphql/typeDefs.ts
#
We created a single root-level listing
field that can be queried from the client to receive the information for a certain listing. The listing
query field queries for a listing in the "listings"
collection of our database based on the id
argument provided.
type Query {
authUrl: String!
user(id: ID!): User!
listing(id: ID!): Listing!
}
The Listing
object returned from the listing
query field is to have certain information about a listing we want the client to access.
type Listing {
id: ID!
title: String!
description: String!
image: String!
host: User!
type: ListingType!
address: String!
city: String!
bookings(limit: Int!, page: Int!): Bookings
bookingsIndex: String!
price: Int!
numOfGuests: Int!
}
src/graphql/resolvers/Listing/index.ts
#
In the listingResolvers
map in the src/graphql/resolvers/Listing/index.ts
file, we created the root-level query listing()
resolver function to find a certain listing from the "listings"
collection based on the id
argument provided. If the viewer making the request is the user who owns the listing (i.e. is the host of the listing), we add an authorized
property to the listing
object to constitute that the viewer is authorized to see certain information about the listing.
export const listingResolvers: IResolvers = { Query: {
listing: async (
_root: undefined,
{ id }: ListingArgs,
{ db, req }: { db: Database; req: Request }
): Promise<Listing> => {
try {
const listing = await db.listings.findOne({ _id: new ObjectId(id) });
if (!listing) {
throw new Error("listing can't be found");
}
const viewer = await authorize(db, req);
if (viewer && viewer._id === listing.host) {
listing.authorized = true;
}
return listing;
} catch (error) {
throw new Error(`Failed to query listing: ${error}`);
}
}
},};
We've added a few other explicit resolver functions for the Listing
GraphQL object.
The
id()
resolver returns the string representation of the_id
value of a listing document.The
host()
resolver attempts to returns a user object for thelisting.host
id value.listing.id
represents theid
of the user who owns the listing.The
bookingsIndex()
resolver returns a string representation of thelisting.bookingsIndex
map object.The
bookings()
resolver returns the list of bookings that have been made to the listing.
This page is a preview of TinyHouse: A Fullstack React Masterclass with TypeScript and GraphQL - Part Two