Skip to content

Commit d0a2eeb

Browse files
fixed slug creation when overwrite = true
1 parent 4b4e769 commit d0a2eeb

File tree

2 files changed

+25
-19
lines changed

2 files changed

+25
-19
lines changed

server/helper/get-unique-slug.js

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,28 @@
1-
const getUniqueSlug = (service, slug, count) => {
1+
const getUniqueSlug = (service, slug, count, id) => {
22
return new Promise(resolve => {
3-
const testslug = count?slug+count:slug;
3+
const testSlug = count ? slug + count : slug;
44

55
// Test if we already have data with this slug
6+
const query = {
7+
slug: testSlug
8+
};
9+
// ignore entry with given id (if set)
10+
if (id) {
11+
query._id = {
12+
$ne: id
13+
};
14+
}
615
service.find({
7-
query: {
8-
slug: testslug
9-
}
16+
query
1017
}).then((result) => {
11-
if(result.data.length > 0) {
12-
count = count?count+1:1;
18+
if (result.data.length > 0) {
19+
count = count ? count + 1 : 1;
1320
resolve(getUniqueSlug(service, slug, count));
1421
} else {
15-
resolve(testslug);
22+
resolve(testSlug);
1623
}
1724
});
1825
});
1926
};
2027

21-
module.exports = getUniqueSlug;
28+
module.exports = getUniqueSlug;

server/hooks/create-slug.js

Lines changed: 9 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,27 +1,26 @@
11
// https://www.npmjs.com/package/slug
22
const slug = require('slug');
33
const getUniqueSlug = require('../helper/get-unique-slug');
4-
const _ = require('lodash');
4+
const { isEmpty } = require('lodash');
55

66
module.exports = function (options = { field: null, overwrite: false }) {
77
return function (hook) {
8-
if(!options.field || !hook.data[options.field]) return hook;
8+
if (!options.field || !hook.data[options.field]) return hook;
99

1010
// do not overwrite existing slug
1111
// TODO: we should make that possible and relying on ids for routing instead only on slugs
1212
// the slug should be there for seo reasons but the id should be what counts
13-
if (!_.isEmpty(hook.data.slug) && options.overwrite !== false) return hook;
13+
if (!isEmpty(hook.data.slug) && options.overwrite !== true) return hook;
1414

1515
return new Promise(resolve => {
16-
17-
const titleslug = slug(hook.data[options.field], {
16+
const titleSlug = slug(hook.data[options.field], {
1817
lower: true
1918
});
20-
21-
getUniqueSlug(hook.service, titleslug).then((uniqueslug) => {
22-
hook.data.slug = uniqueslug;
23-
resolve(hook);
24-
});
19+
getUniqueSlug(hook.service, titleSlug, null, hook.id)
20+
.then((uniqueSlug) => {
21+
hook.data.slug = uniqueSlug;
22+
resolve(hook);
23+
});
2524
});
2625
};
2726
};

0 commit comments

Comments
 (0)