Skip to content

Instantly share code, notes, and snippets.

@jerryjappinen
Last active February 15, 2022 18:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jerryjappinen/0982596512e6670196029ee523491232 to your computer and use it in GitHub Desktop.
Save jerryjappinen/0982596512e6670196029ee523491232 to your computer and use it in GitHub Desktop.
Scoped uniqueness on 8base via triggers
# https://docs.8base.com/docs/8base-console/custom-functions/triggers/
functions:
beforeProjectCreate:
handler:
code: triggers/beforeProjectCreate.js
type: trigger.before
operation: Project.create
description: Enforce unique Project slugs within a team upon create
beforeProjectUpdate:
handler:
code: triggers/beforeProjectUpdate.js
type: trigger.before
operation: Project.update
description: Enforce unique Project slugs within a team upon update

Scoped uniqueness on 8base via triggers

Rough example for how to achieve fields that have unique values within a relation, for example, projects with unique slugs within a team.

async function slugExists (api, teamId, slug) {
const response = await api.gqlRequest(`{
projectsList (
filter: {
slug: {
equals: "${slug}"
}
team: {
id: {
equals: "${teamId}"
}
}
}
) {
items {
id
}
}
}`)
return response.projectsList.items && response.projectsList.items.length
}
export default async ({ data }, { api }) => {
if (
data.slug &&
data.team.connect.id &&
await slugExists(api, data.team.connect.id, data.slug)
) {
throw new Error('Project\'s slug must be unique within a team')
}
return {
data
}
}
async function slugExistsByProjectId (api, projectId, slug) {
const response = await api.gqlRequest(`{
project(
id: "${projectId}"
) {
team {
projects (
filter: {
slug: {
equals: "${slug}"
}
}
) {
items {
id
}
}
}
}
}`)
return response.project.team.projects.items && response.project.team.projects.items.length
}
export default async ({ data, originalObject }, { api }) => {
if (
data.slug !== originalObject.slug &&
await slugExistsByProjectId(api, originalObject.id, data.slug)
) {
throw new Error('Project\'s slug must be unique within team')
}
return {
data
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment