Is it possible to attach to the response a variabl...
# orm-help
j
Is it possible to attach to the response a variable that isn't in the database? So I was thinking like maybe when returning User i could query for the name, username etc and after that query about an average number of Likes for example. Since can't do the aggregation with prisma was thinking doing it manually and attach that result to the response when asked
u
Actually, the application layer is just for that. You can provide you custom resolver and implement any logic in it
f
Yes, the type in the DB can be different from the type in the application. Make a new User type with that extra field in the application schema. It would be nice to “extend” the database/Prisma type in the application layer and just add/remove the extra information, but I don’t think this is possible.
j
@usukhbayar @Fran Dios But how would you achieve something like this? I have no clue on doing that. So for example i have this
Copy code
me(parent, args, ctx, info) {
    const id = getUserId(ctx);
    return ctx.db.query.user({ where: { id } }, info);
  }
When this user is returned i want to attach an extra filed on the response if it's being asked. In the schema i declared it like ``rateAVG: Float`` and this should return a float number based on the avg function. So to calculate the average i was thinking on raw sql or maybe something like this
Copy code
let rates = ctx.db.query.rates({});
    let sum = 0;
    for (let i = 0; i < rates.length; i++) {
      sum += rates[i];
    }

    let average =  rates.length != null ? sum / rates.length : 0;
But no clue on how to achieve that, thanks for the help tho
j
Instead of returning the query directly, which is a promise, make your resolver an async function, and call the query asynchronously :
Copy code
async me(parent, args, ctx, info) {
  const id = getUserId(ctx);
  const user = await ctx.db.query.user({ where: { id } }, info);
  const average = //... Do your thing.
  return {
    ...user,
    average
  };
}
🔑 1
If this field is computed, there is no need to put it in the prisma schema. Inside your app schema (generally named schema.graphql), you can create a new type, copying the user fields and adding your new field there :
Copy code
type CustomUser {
  # ... fields from User type
  average: Float
}
And also the query should return this type instead of User :
Copy code
type Query {
  #... other queries
  me: CustomUser
}