Is it possible / advisable to convert an array to ...
# orm-help
j
Is it possible / advisable to convert an array to a single item in a resolver? My resolver returns an array, but I know that there will always be a single result. Is it possible to modifiy the resolver to reutrn a single result? This is my resolver:
Copy code
location(parent, args, ctx, info) {
   const { machineName } = args;
   return ctx.db.query.locations({ where: { machineName } }, info);
 }
This query from the front-end:
Copy code
{
  location(machineName: "london") {
    id
    name
    
  }
}
Will return:
Copy code
{
  "data": {
    "location": [
      {
        "id": "cjgrqosbt5eum0b51hz4yqrou",
        "name": "London"
      }
    ]
  }
}
But id like something like:
Copy code
{
  "data": {
    "location" {
      "id": "cjgrqosbt5eum0b51hz4yqrou",
      "name": "London"
    }
  }
}
h
Copy code
async location(parent, args, ctx, info) {
  const { machineName } = args;
  const res = await ctx.db.query.locations({ where: { machineName } }, info);
  return res[0];
}
c
Or use
Copy code
ctx.db.query.location({where: {machineName}}, info);
m
Is there a ‘location’ query that you could use instead? If you are SURE that there will never be two machines with the same name, you should put a unique constraint on machineName. If you do this, you will be able to use the single ‘location’ query. If you are not sure that making machineName unique is the right move, you should write code that anticipates the result to have more than one value (ie use map, which will work with one or multiple values) that way you don’t run in to problems down the line when you forget that you hardcoded a zero in your resolver.
👍 2
😀 1
n
@Jim the key aspect is that your application schema should reflect the contract towards the client. So, you should probably define the return type of your outwards query as a single node of type
Location
. That you are using the
locations
query (which returns a type
[Location!]!
) internally is an implementation detail and shouldn't dictate your client facing API.
👍 3