Ability to connect if exists, otherwise create in GraphQL mutations

So here’s what I came up with.
It’s working properly for my use case. The difference with yours is mainly that I iterate over an array of FileMeta instead of just one.
In the end, I also only return the shas that have been created, not the ones that have been connected.

Thanks again for your help.
Here is my code if it is of any help out there.

Query(
        Lambda(
          ['commitSha', 'filesMeta'],
          Let(
            {
              newGitRef: Create(Collection('GitRef'), {
                data: { commitSha: Var('commitSha') },
              }),
            },
            Filter(
              Map(
                Var('filesMeta'),
                Lambda(
                  ['fileMeta'],
                  Let(
                    {
                      fileMetaRef_maybe: Match(
                        Index('unique_FileMeta_sha'),
                        Select(['sha'], Var('fileMeta')),
                      ),
                    },
                    If(
                      Exists(Var('fileMetaRef_maybe')),
                      Do(
                        Create(Collection('fileMeta_gitRefs'), {
                          data: {
                            gitRefID: Select(['ref'], Var('newGitRef')),
                            fileMetaID: Select(
                              ['data', 0],
                              Paginate(Var('fileMetaRef_maybe')),
                            ),
                          },
                        }),
                        null,
                      ),
                      Let(
                        {
                          newFileMeta: Create(Collection('FileMeta'), {
                            data: Var('fileMeta'),
                          }),
                          link: Create(Collection('fileMeta_gitRefs'), {
                            data: {
                              gitRefID: Select(['ref'], Var('newGitRef')),
                              fileMetaID: Select(['ref'], Var('newFileMeta')),
                            },
                          }),
                        },
                        Select(['data', 'sha'], Var('newFileMeta')),
                      ),
                    ),
                  ),
                ),
              ),
              // only returns the created files sha
              Lambda(['nullOrCreated'], Not(IsNull(Var('nullOrCreated')))),
            ),
          ),
        ),
      )

Also my feedback to have upnect built in the GraphQL engine still stands :wink:

1 Like