Search code examples
graphqlapolloapollo-serverkeystonejs

How do I pass a string to a GraphQL query when it's expecting an enum (Apollo Server)?


I'm trying to make a GraphQL query inside a KeystoneJS app where I need to determine if a page of a certain type exists (if a page of that type exists, I won't create it -- I'm implementing each page type as a singleton). My thinking was to do a search for all pages with a where condition where I pass the type of the page I'm trying to create.

const PAGE_QUERY = `
    query allPages($where:PageWhereInput){
      allPages(where:$where) {
    pageType
  }
}
`;

export const doesPageTypeExist = async (query, articleType: string): Promise<boolean> => {
    const where = {
        pageType: articleType
    };
    const options = {
        skipAccessControl: false,
        variables: {
            where
        }
    };
    const { errors, data } = await query(allPages, options);
    if (errors) {
        log.error({ errors }, 'errors from GraphQL operation in Page list');
        throw new Error(errors.toString());
    } else {
        return data?.allPages.length !== 0;
    }
};

The problem is that I get the error

Variable "$where" got invalid value { pageType: "page2" } at "where.pageType"; Expected type PagePageTypeType.

I understand where the error is coming from: it's expecting one of these enum's

enum CondomPagePageTypeType {
 page1
 page2
 page3
 page4
}

and I'm passing it a string, but I don't know how to pass the value I'm testing (which comes from Keystone) except as a string.


Solution

  • Enum values are always serialized as strings when used as variables, so the problem is not with how the enum value is being submitted. According to the error, the issue is with the value of the pageType property of $where. It appears that the value of pageType is actually the object { pageType: "page2" } and not page2. In other words, your variables property looks like this:

    {
      "where": {
        "pageType": {
          "pageType": "page2"
        }
      }
    }
    

    Based on the shown code, I'd guess that maybe the articleType parameter being passed to doesPageTypeExist is not actually a string like its type would indicate.