GraphQL预约系统中嵌套对象数组Resolver开发问题咨询
Let’s break down how to get that assignedStaff resolver working with your mock data—since you already have the other associations sorted, this should fit right in with your existing setup.
First, let’s assume your GraphQL Schema looks something like this (adjust if your actual types differ slightly):
type Staff { id: ID! name: String! role: String! } type Account { id: ID! email: String! } type Booking { id: ID! account: Account! assignedStaff: [Staff!]! date: String! } type Query { getBooking(id: ID!): Booking }
Step 1: Structure Your Mock Data for Association
For the resolver to work cleanly, your mock bookings should store Staff IDs (not full Staff objects) in an array—this mirrors how you’d structure data in a real database. Here’s an example:
// Mock datasets const mockStaff = [ { id: 's1', name: 'Mia Carter', role: 'Lead Stylist' }, { id: 's2', name: 'Jake Torres', role: 'Barber' }, { id: 's3', name: 'Lila Chen', role: 'Esthetician' } ]; const mockBookings = [ { id: 'b1', accountId: 'a1', assignedStaffIds: ['s1', 's3'], // Link to Staff IDs here date: '2024-06-15' } ]; const mockAccounts = [ { id: 'a1', email: 'client@example.com' } ];
Step 2: Implement the AssignedStaff Resolver
The key here is using the parent parameter in the resolver—it gives you access to the current Booking object, so you can pull the Staff IDs and fetch matching Staff entries from your mock data.
Add this to your existing resolvers:
const resolvers = { Query: { getBooking: (_, { id }) => mockBookings.find(booking => booking.id === id) }, Booking: { // Your existing working account resolver account: (parent) => mockAccounts.find(acc => acc.id === parent.accountId), // The new assignedStaff resolver assignedStaff: (parent) => { // Filter mockStaff to only include entries with IDs in the booking's assignedStaffIds return mockStaff.filter(staff => parent.assignedStaffIds.includes(staff.id)); } } };
Why This Works
- The
parentargument in theBooking.assignedStaffresolver is the full Booking object returned from the Query resolver. - We use
filter()to match Staff IDs from the booking’sassignedStaffIdsarray to entries in themockStaffdataset. - This pattern scales seamlessly to real databases later—just replace the
filter()with a database query (e.g.,Staff.find({ _id: { $in: parent.assignedStaffIds } })for MongoDB).
Quick Check
If your mock data already includes full Staff objects nested in the Booking, you might not even need a resolver—double-check that your Schema’s assignedStaff type matches the data you’re returning. But using ID-based associations is better practice for maintainability.
内容的提问来源于stack exchange,提问作者Drum

