Neo4j-graphql-js -- Is there a way to check if an optional parameter exists or is not null?

323 views Asked by At

This is a simplified example, but I am attempting to make a change to my schema that is backwards compatible with older versions of the app. I am adding an externalUrls parameter:

CreatePost(body: String!, userId: ID!, mentions: [String!], linkUrl: String, externalUrls: [String]): Post @isAuthenticated
    @cypher(
      statement: """
        ...
        UNWIND $externalUrls as urlText
        CREATE (link:Link {
            id: apoc.create.uuid(),
            path: urlText,
            createdAt: datetime(),
            updatedAt: datetime()
        })
        CREATE (link)-[:LINKS_TO {createdAt: datetime()}]->(post)
        RETURN post
    """)

There is some cypher before that, but the idea is that I want to only run this code:

UNWIND $externalUrls as urlText
CREATE (link:Link {
    id: apoc.create.uuid(), 
    path: urlText,
    createdAt: datetime(),
    updatedAt: datetime()        
})
CREATE (link)-[:LINKS_TO {createdAt: datetime()}]->(post)

if $externalUrls exists/is not null. If an older version of the app calls

mutation CreatePost($body: String!, $userId: ID!, $mentions: [String!], $linkUrl: String) {
  CreatePost(body: $body, userId: $userId, mentions: $mentions, linkUrl: $linkUrl) {
    id
  }
}

Where the $externalUrls: [String] is not even able to be passed in, the UNWIND line breaks. I've tried using CALL apoc.do.when and FOREACH to check if EXISTS($externalUrls) or NOT $externalUrls IS NULL and both fail when that is not even passed in as an argument. Is there another way to check if an argument has any value or exists? My sense is that I'm going to always run into Expected parameter(s): externalUrls, but I would love to find a way to avoid that.

1

There are 1 answers

0
InverseFalcon On

If you use a parameter in the query, then the parameter is required.

The best way to mimic optional parameters is to pass a map parameter, and use the entries in the map.

For example, if you pass in:

$myParams = {externalUrls:null, someOtherEntry:1, etc:true}

Then you can reference: $myParams.externalUrls, or use a WHERE clause on it, or a CASE, to take some action on it for whether it's null or not.