Skip to content

Commit 71dca85

Browse files
author
Farhan Hasin Chowdhury
committed
Implemented update middlewares
1 parent 45869a4 commit 71dca85

File tree

1 file changed

+13
-21
lines changed

1 file changed

+13
-21
lines changed

lib/simple-slugify.js

Lines changed: 13 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -2,37 +2,29 @@
22

33
const crypto = require('crypto');
44

5-
async function makeSlug(source, doc) {
6-
const regex = /[&/\\#,+()$~%.'":*?<>{} ]/g;
7-
8-
let slug = doc[source].toString().toLowerCase().trim().replace(regex, '-');
9-
10-
try {
11-
slug = (await doc.model(doc.constructor.modelName).exists({ slug }))
12-
? `${slug}-${crypto.randomBytes(5).toString('hex')}`
13-
: slug;
14-
} catch (error) {
15-
// eslint-disable-next-line no-console
16-
console.log(error);
17-
}
18-
19-
return slug;
20-
}
5+
const regex = /[&/\\#,+()$~%.'":*?<>{} ]/g;
216

227
module.exports = function (schema) {
238
schema.pre(['save', 'updateOne'], async function (next) {
249
const { source } = schema.tree.slug;
2510

26-
const doc = this;
11+
let slug = this[source].toString().toLowerCase().trim().replace(regex, '-');
12+
13+
try {
14+
slug = (await this.model(this.constructor.modelName).exists({ slug }))
15+
? `${slug}-${crypto.randomBytes(5).toString('hex')}`
16+
: slug;
17+
} catch (error) {
18+
// eslint-disable-next-line no-console
19+
console.log(error);
20+
}
2721

28-
this.slug = await makeSlug(source, doc);
22+
this.slug = slug;
2923

3024
next();
3125
});
3226

33-
schema.pre(['findOneAndUpdate'], async function (next) {
34-
const regex = /[&/\\#,+()$~%.'":*?<>{} ]/g;
35-
27+
schema.pre(['update', 'findOneAndUpdate'], async function (next) {
3628
let slug = this.get(this.schema.tree.slug.source)
3729
.toString()
3830
.toLowerCase()

0 commit comments

Comments
 (0)