Generate Slugs with Flows

Generate Slugs with Flows

const slugify = text =>
  text
    .toString()
    .normalize('NFD')
    .replace(/[\u0300-\u036f]/g, '')
    .toLowerCase()
    .trim()
    .replace(/\s+/g, '-')
    .replace(/[^\w-]+/g, '')
    .replace(/--+/g, '-');

module.exports = async function(data) {
    // if title not passed
    if (data.$trigger.payload.title === undefined) return data.$trigger.payload;
    // if user entered slug themselves...
    if (data.$trigger.payload.slug !== undefined) return data.$trigger.payload;
    /// generate slug
    const slug = slugify(data.$trigger.payload.title);
    return {...data.$trigger.payload, slug};
}

How to Use it

For this example, we'll create a collection called posts, and inside this collection, we'll add two input fields:

  1. title
  2. slug

Now go to flows and create a new flow.

Set the flow to blocking, to run during create and update, (or just on create).

Drag the arrow and choose run script.

Now when a new post is created or a post is updated, the flow will run and update the slug field as long as the title isn't empty and the slug is also empty.

Do you like my content?

Sponsor Me On Github