hayes / pothos

Pothos GraphQL is library for creating GraphQL schemas in typescript using a strongly typed code first approach
https://pothos-graphql.dev
ISC License
2.35k stars 163 forks source link

Custom sort data array based on a calculated prismaObject field #1303

Open dylanlarrivee opened 2 months ago

dylanlarrivee commented 2 months ago

Hi, I was wondering if it is possible to sort the array of data being returned by my resolver based on a calculated prismaObject field.

I have a field in my prismaObject that I am populating with a name based off of an id using a db lookup in a separate db (this connection is not used the prisma plugin) so I am unable to use the prisma sort logic as I normally would as that logic could sit in my prismaField resolve function.

I was hoping there was a way to implement so custom sorting logic on the data after pothos has created the object based off of the db data that get returned.

Thanks,

hayes commented 2 months ago

I am not sure if I am understanding the question correctly, but you could probably do something like this:

 t.field({
   type: [RelatedType],
   select: {
     yourRelation:true,
     yourField: true
   },
   resolve: (parent) => {
     return parent.yourRelation.sort(sortFromField(parent.yourField) })
   },
 })
dylanlarrivee commented 2 months ago

Ok yea, I feel like this setup could work. Is there a way I can pass any sort of args down to this field that could be used to identify which filed to sort on? I am using this for a table display and trying to provide the option to sort on each table column.

hayes commented 2 months ago
t.field({
   type: [RelatedType],
   args: {
     orderBy: t.arg({ field: YourOrderByType }),
   },
   select: {
     yourRelation:true,
   },
   resolve: (parent, args) => {
     return parent.yourRelation.sort(sortFromField(args.orderBy) })
   },
 })
dylanlarrivee commented 2 months ago

Awesome, I think this is just what I need. I will post my finished code here shortly in case anyone else is trying to do the same thing. Thanks!