All files / mongoose-slug-updater/lib slug-generator.js

100% Statements 325/325
94.47% Branches 188/199
100% Functions 51/51
100% Lines 309/309

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723  1x   1x 1x 1x   1x 34x                   34x     58x 58x 414x 24x               390x         226x 18x 18x 18x 18x 36x 10x 10x 10x 10x     18x 10x         18x 6x 6x 6x       18x 2x 2x 2x       18x 6x 6x 6x       18x   34x 390x         226x 226x 226x 226x                         226x 214x 12x 10x   2x 2x   224x 41x   224x 2x     224x 191x   33x 33x   224x 18x 12x   6x     224x 3x 3x 3x   224x       34x 19x     34x 141x     34x 42x     34x 119x       321x   321x 321x 321x 61x 2143x   61x   321x   321x 321x 12x     309x       309x   21180x     26700x   309x         26700x       309x 274x 102x 274x 235x 235x 18168x 18168x 18176x 13699x     235x       309x 309x   4155x 4155x 4155x                                 4155x   309x 345x 345x 345x 235x   8416x   7496x     235x 14335x   15055x           345x 292x   345x 345x 19681x 19681x   345x 235x 14335x 2075x 2075x         345x 345x 83x     9367x 9367x   83x     345x 305x             40x 40x           34x 1719x 1719x 1719x 1491x       228x 228x   228x 34x     194x         1547x 1547x 1547x                 7476x 7476x 7476x 6064x   6064x 6064x                               7476x   7476x 7476x 7476x               7476x   7476x   7476x   6064x 6064x 6064x 6064x   6064x 6064x 1582x   1582x 1582x 1582x   1582x   1582x     4482x 4482x                                           5894x 5894x 5894x 5774x 5774x 5774x 3696x 3624x       72x     5774x 5702x 5702x   72x     5894x 5702x 5702x 5702x   653x   5049x 40811x 40811x     5049x             5894x                         1x 218759x 1x 25167x 1x 49420x         894x 894x 25405x 25405x 25405x   25405x 25405x 49378x 49378x   51326x 51326x 51326x 9770x 9770x 9770x 7016x 7016x   9770x 7016x 7016x     9770x 9770x 9770x 9770x 9770x   51326x 20018x         51326x 15222x       51326x   49378x 49378x     49378x   49420x     48486x 48486x 48486x 48486x 48486x 48486x       894x       115954x 48622x 48622x 48622x     115954x 115954x   115954x 7600x 67332x 67332x     108354x   115954x                 486x   25171x   25171x 25314x   25171x 25171x       17695x 17691x   17695x   7476x 7476x 7476x 694x 694x     7476x 7476x 3797x                               3679x                                       486x       25167x   25167x     3292x 3292x 3292x   3292x 3128x   3292x                           3679x 3679x 3679x   3679x                     3679x 3292x 3292x   3679x   3679x                           3797x 3797x   3797x                     3797x   3339x 3339x           278x 3061x   458x 34x     3797x   3797x    
'use strict';
const _ = require('deepdash')(require('lodash'));
 
const fs = require('fs');
var getSlug = require('speakingurl'),
  shortId = require('shortid');
 
module.exports = function plugin(schema, options) {
  options = _.merge(
    {
      separator: '-',
      lang: 'en',
      truncate: 120,
      backwardCompatible: true,
    },
    options
  );
 
  var slugs = [];
 
  function schemaTraversal(schema, basePath, cb) {
    if (basePath) basePath += '.';
    schema.eachPath(function(schemaPath, schemaType) {
      if (schemaType.caster && schemaType.caster.schema) {
        schemaTraversal(
          schemaType.caster.schema,
          basePath +
            schemaPath +
            (schemaType.constructor.schemaName == 'DocumentArray' ? '.$' : ''),
          cb
        );
      } else {
        cb(basePath + schemaPath, schemaType);
      }
    });
  }
  function renameOldOptions(opts) {
    if (!options.backwardCompatible) return opts;
    let res = _.cloneDeep(opts);
    let deprecated = ['unique_slug', 'slug_padding_size'];
    let found = [];
    _.each(deprecated, oldo => {
      if (res[oldo] !== undefined) {
        let newo = _.camelCase(oldo);
        found.push([oldo, newo]);
        res[newo] = res[oldo];
        delete res[oldo];
      }
    });
    if (found.length) {
      console.log(
        'Deprecated "snake_case" options found by slug updater plugin. Please update to camelCase.',
        found
      );
    }
    if (res.uniqueGroup) {
      res.uniqueGroupSlug = res.uniqueGroup;
      delete res.uniqueGroup;
      console.log(
        'Deprecated option "uniqueGroup" found by slug updater. Please update to uniqueGroupSlug.'
      );
    }
    if (res.force_id) {
      res.forceIdSlug = res.force_id;
      delete res.force_id;
      console.log(
        'Deprecated option "force_id" found by slug updater. Please update to forceIdSlug.'
      );
    }
    if (res.on) {
      res.slugOn = res.on;
      delete res.on;
      console.log(
        'Deprecated option "on" found by slug updater. Please update to slugOn.'
      );
    }
    return res;
  }
  schemaTraversal(schema, '', (schemaPath, schemaType) => {
    if (
      schemaType.instance == 'String' &&
      schemaType.options &&
      schemaType.options.slug
    ) {
      let opts = renameOldOptions(schemaType.options);
      let basePath = schemaPath.replace(/[\.][^\.]+$/, '');
      if (basePath == schemaPath) basePath = '';
      var slug = {
        path: schemaPath,
        basePath,
        on: {
          save: true,
          update: true,
          updateOne: true,
          updateMany: true,
          findOneAndUpdate: true,
          ...(opts.slugOn || {}),
        },
      };
 
      if (typeof opts.slug === 'string') {
        slug.fields = [opts.slug];
      } else if (opts.slug instanceof Array) {
        slug.fields = opts.slug;
      } else {
        console.warn(`slug option expected to be string or array. ${typeof opts.slug} found and will be ignored.`);
        return;
      }
      if (opts.unique || opts.uniqueSlug) {
        slug.unique = true;
      }
      if (opts.permanent) {
        slug.permanent = true;
      }
 
      if (opts.slugPaddingSize === undefined) {
        slug.isShortIdMode = true;
      } else {
        slug.isShortIdMode = false;
        slug.padding = opts.slugPaddingSize;
      }
      if (opts.uniqueGroupSlug) {
        if (_.isArray(opts.uniqueGroupSlug)) {
          slug.uniqueGroupFields = opts.uniqueGroupSlug;
        } else {
          slug.uniqueGroupFields = [opts.uniqueGroupSlug];
        }
      }
      if (opts.forceIdSlug) {
        slug.unique = true;
        slug.isShortIdMode = true;
        slug.forceShortId = true;
      }
      slugs.push(slug);
    }
  });
  // console.log(slugs);
  schema.pre('update', async function() {
    return onUpdate.bind(this)('update');
  });
 
  schema.pre('updateOne', async function() {
    return onUpdate.bind(this)('updateOne');
  });
 
  schema.pre('updateMany', async function() {
    return onUpdate.bind(this)('updateMany');
  });
 
  schema.pre('findOneAndUpdate', async function() {
    return onUpdate.bind(this)('findOneAndUpdate');
  });
 
  async function onUpdate(operation) {
    const me = this;
    // console.log(` = ${operation} ${me.model.modelName} = \n`);
    let upd = me.getUpdate();
    let doc = _.cloneDeep(upd);
    if (doc.$set) {
      _.forOwn(doc.$set, (v, k) => {
        _.set(doc, k, v);
      });
      delete doc.$set;
    }
    let docs = [_.cloneDeep(doc)];
 
    let unwoundSlugs = unwindSlugs(doc, _.filter(slugs, `on.${operation}`));
    if (!unwoundSlugs.length) {
      return;
    }
 
    let updFields = _.keysDeep(doc);
    // let updPaths = _.map(updFields, f =>
    //   _.trim(f.replace(/\["?(.+?)"?\]/g, '.$1'), '.')
    // );
    let involvedPaths = _.uniq(
      unwoundSlugs.reduce(
        (acc, slug) => acc.concat(slug.fields).concat([slug.path]),
        []
      )
    ).map(p => p.replace(/^\//, ''));
 
    let involvedValuesDocs = await me.model[
      operation == 'updateOne' ? 'findOne' : 'find'
    ](
      me.getQuery(),
      _(involvedPaths)
        .map(k => [k.replace(/\.[$\d]+\./g, '.'), 1])
        .fromPairs()
        .value()
    );
    if (involvedValuesDocs) {
      if (!_.isArray(involvedValuesDocs))
        involvedValuesDocs = [involvedValuesDocs];
      involvedValuesDocs.forEach((freshDoc, i) => {
        if (i) docs[i] = _.cloneDeep(doc);
        involvedPaths.forEach(function(f) {
          let fs = unwindPath(freshDoc, f);
          _.each(fs, f => {
            if (_.get(docs[i], f) === undefined)
              _.set(docs[i], f, _.get(freshDoc, f));
          });
        });
        Eif (freshDoc && freshDoc._id) docs[i]._id = freshDoc._id;
      });
    }
 
    let slugsUpd = [];
    let cache = {};
    async function findOne(query, sort) {
      let res = me.model.findOne(query);
      Eif (sort) {
        res = res.sort(sort);
      }
      // res = await res;
      // if (slugsUpd.length && sort) {
      //   let field = _.first(_.keys(sort));
      //   let top = _.maxBy(slugsUpd, u => {
      //     return extractCounter(_.get(u, field), options.separator);
      //   });
      //   if (_.has(top, field)) {
      //     let localCounter = extractCounter(
      //       _.get(top, field),
      //       options.separator
      //     );
      //     let dbCounter = extractCounter(res.get(field), options.separator);
      //     if (localCounter > dbCounter) res = top;
      //   }
      // }
      return res;
    }
    for (let i = 0; i < docs.length; i++) {
      let currentUnwoundFields = unwindSlugs(docs[i], unwoundSlugs);
      let actualSlugs = currentUnwoundFields;
      if (involvedValuesDocs && involvedValuesDocs.length) {
        let actualUpdFields = _(updFields)
          .filter(f => {
            return _.get(doc, f) != _.get(involvedValuesDocs[i], f);
          })
          .map(f => _.trim(f.replace(/\["?(.+?)"?\]/g, '.$1'), '.'))
          .value();
 
        actualSlugs = _.filter(currentUnwoundFields, s => {
          return _.intersection(
            _.map(s.fields.concat(s.uniqueGroupFields || []), p =>
              p.replace(/^\//, '')
            ),
            actualUpdFields
          ).length;
        });
      }
      if (actualSlugs.length) {
        await setSlugs(docs[i], actualSlugs, options, findOne, cache);
      }
      slugsUpd[i] = _.cloneDeep(upd.$set || upd);
      actualSlugs.forEach(slug => {
        let slugVal = _.get(docs[i], slug.path);
        Eif (slugVal != undefined) _.set(slugsUpd[i], slug.path, slugVal);
      });
      if (involvedValuesDocs && involvedValuesDocs.length) {
        _.each(currentUnwoundFields, us => {
          if (_.get(slugsUpd[i], us.path) === undefined) {
            let val = _.get(involvedValuesDocs[i], us.path);
            Eif (val !== undefined) _.set(slugsUpd[i], us.path, val);
          }
        });
      }
 
      let doUpd = slugsUpd[i];
      if (upd.$set) {
        let slugPaths = _(slugsUpd[i])
          .indexate({ leafsOnly: true })
          // .mapValues(v=>_.isArray(v)?[]:(_.isObject(v)?{}:v))
          .mapKeys((v, f) => _.trim(f.replace(/\["?(.+?)"?\]/g, '.$1'), '.'))
          .omitBy(v=>v===undefined)
          .value();
        doUpd = { $set: slugPaths };
      }
 
      if (docs.length == 1) {
        Eif (slugsUpd[i]) me[operation]({}, doUpd);
      } else {
        // Mongoose doesn't support docs without _id
        // if (!docs[i]._id)
        //   throw new Error(
        //     'Cannot update slug massively, because _id not found for each doc.'
        //   );
        Eif (doUpd) {
          await me.model.updateOne({ _id: docs[i]._id }, doUpd);
        }
      }
    }
    // console.log(me.getUpdate());
  }
  schema.pre('save', async function() {
    let cache = {};
    let doc = this;
    if (!doc.model) {
      return;
    }
    // console.log(` = save ${doc.constructor.modelName} = \n`);
    // console.log(doc);
    let reSlug = false;
    let unwoundSlugs = unwindSlugs(doc, _.filter(slugs, 'on.save'));
 
    if (!unwoundSlugs.length) {
      return;
    }
 
    doc = await setSlugs(
      doc,
      unwoundSlugs,
      options,
      async (query, sort) => {
        let res = doc.model(doc.constructor.modelName).findOne(query);
        Eif (sort) res = res.sort(sort);
        return res;
      },
      cache
    );
    // console.log(doc);
  });
};
function updateUpdCache(cache, path, slug, value) {
  // console.log(`updateUpdCache ${path}: ${slug}`);
  let maskedPath = path.replace(/\.[$\d]+\./g, '.$.');
  let isArrayPath = path != maskedPath;
  if (isArrayPath) {
    let localKey = maskedPath + ':' + slug;
    // console.log(`${path} resolves ${cache.upd[localKey].ext.path} with ${value}  \n${localKey}`);
    cache.lock[path].ext.resolveEx(value);
    delete cache.lock[path];
  }
}
async function findSame(
  cache,
  doc,
  group,
  path,
  slug,
  isCounter,
  options,
  findOne,
  //slugsMdfPaths
) {
  // console.log(`findSame#${doc.n} ${path}: ${slug}`);
  // console.log(cache);
  cache = _.merge(cache, { db: {}, unwind: {}, upd: {}, lock:{} });
  // console.log(cache);
  let maskedPath = path.replace(/\.[$\d]+\./g, '.$.');
  let isArrayPath = path != maskedPath;
  let slugRx = new RegExp(
    '^' +
      slug +
      '(' +
      options.separator +
      (isCounter ? '(\\d+)' : '(.+)') +
      ')?$'
  );
  let localKey = maskedPath + ':' + slug;
  // console.log(`findSame#${doc.n} localKey: \n${localKey}`);
  let key = localKey + '-' + JSON.stringify(group);
  // let candidates = [];
  if (isArrayPath) {
    // console.log('array? maskedPath', maskedPath);
    let ext = { path };
    let updPromise = new Promise((resolve, reject) => {
      ext.resolveEx = resolve;
      ext.rejectEx = reject;
    });
    updPromise.ext = ext;
    if (cache.upd[localKey] !== undefined) {
      let res = cache.upd[localKey];
      // console.log(`${path} put lock \n${localKey}`);
      cache.upd[localKey] = updPromise;
      let fromPath = res.ext.path;
      cache.lock[path] = updPromise;
      // console.log(`${path} waits for ${fromPath} \n${localKey}`);
      res = await res;
      // console.log(`${path} got ${fromPath}  \n${localKey}`,res);
      return res;
    } else {
      // console.log(`${path} put lock init \n${localKey}`);
      cache.upd[localKey] = updPromise;
      cache.lock[path] = updPromise;
    }
//     if (cache.unwind[maskedPath] === undefined) {
//       cache.unwind[maskedPath] = {
//         list: _(unwindPath(doc, maskedPath))
//           .map(p => [p, docGet(doc, p)])
//           .filter(([p, v]) => v !== undefined && slugsMdfPaths[p] === undefined)
//           .sortBy('[1]')
//           .value(),
//       };
//     }
// 
//     let top = _(cache.unwind[maskedPath].list)
//       .filter(([p, v]) => p != path && v.match(slugRx))
//       .last();
//     if (top) {
//       // console.log(`unwind cache for ${path}: ${top[1]}`);
//       candidates.push(top[1]);
//     } else {
//       console.log(`no unwind cache for ${path}: `,cache.unwind[maskedPath].list);
//     }
  }
  let query = _.cloneDeep(group);
  let sort = {};
  if (cache.db[key] === undefined) {
    let arrayPath = path.replace(/\.[$\d]+\./g, '.');
    query[arrayPath] = slugRx;
    if (doc._id) {
      if(query['_id']==undefined){
        query['_id'] = {
          $ne: doc._id,
        };
      }else{
        query=false;
      }
    }
    if(query!==false){
      if (isCounter) sort[arrayPath] = -1;
      cache.db[key] = findOne(query, sort);
    }else{
      cache.db[key] = null;
    }
  }
  if (_.isObject(cache.db[key]) && _.isFunction(cache.db[key].then)) {
    let foundDoc = await cache.db[key];
    Eif (_.isObject(cache.db[key]) && _.isFunction(cache.db[key].then)) {
      if (!foundDoc) {
        // console.log('db cache set', path, null, query, sort);
        cache.db[key] = null;
      } else {
        foundDoc = _(unwindPath(foundDoc, maskedPath))
          .map(p => [p, docGet(foundDoc, p)])
          .filter(([p, v]) => v.match(slugRx))
          .sortBy('[1]')
          .last();
        cache.db[key] = foundDoc[1];
        // if (foundDoc) cache.db[key] = foundDoc[1];
        // else cache.db[key] = null;
        // console.log('db cache set', path, cache.db[key], query, sort, group);
      }
    }
  }
  return cache.db[key];
  // if (cache.db[key] !== undefined) {
    // console.log(`db cache for ${path}: ${cache.db[key]}`);
    // candidates.push(cache.db[key]);
  // }
 
  // let res = _(candidates.sort())
  //   .filter(c => c !== null)
  //   .last();
  // // console.log(`${path}: ${res} chosen from `,candidates);
  // return res;
  // return null;
}
let docGet = (doc, path) =>
  _.isFunction(doc.get) ? doc.get(path) : _.get(doc, path);
let docSet = (doc, path, val) =>
  _.isFunction(doc.set) ? doc.set(path, val) : _.set(doc, path, val);
let docIsModified = (doc, path) =>
  _.isFunction(doc.isModified)
    ? doc.isModified(path)
    : _.get(doc, path) !== undefined;
 
function unwindSlugs(doc, slugs) {
  let unwoundSlugs = [];
  slugs.forEach(slug => {
    let slugPaths = unwindPath(doc, slug.path);
    if (!slugPaths.length) slugPaths.push(slug.path);
    let basePath = slug.basePath;
 
    if (_.endsWith(basePath, '.$')) basePath += '.';
    slugPaths.forEach(slugPath => {
      let unwoundBasePath = slugPath.replace(/\.[^\.]+$/, '');
      if (unwoundBasePath == slugPath) unwoundBasePath = '';
      function unwindFieldPath(fieldPath) {
        let slugValueBasePath = unwoundBasePath;
        let originalBasePath = _.trimEnd(basePath, '.');
        while (_.startsWith(fieldPath, ':')) {
          let prevValueBasePath = slugValueBasePath;
          let prevOriginalBasePath = originalBasePath;
          if (slugValueBasePath.match(/\.[$\d]+$/)) {
            slugValueBasePath = slugValueBasePath.replace(/\.[$\d]+$/, '');
            prevValueBasePath = slugValueBasePath;
          }
          if (originalBasePath.match(/\.[$\d]+$/)) {
            originalBasePath = originalBasePath.replace(/\.[$\d]+$/, '');
            prevOriginalBasePath = originalBasePath;
          }
 
          slugValueBasePath = slugValueBasePath.replace(/\.[^\.]+$/, '');
          originalBasePath = originalBasePath.replace(/\.[^\.]+$/, '');
          if (slugValueBasePath == prevValueBasePath) slugValueBasePath = '';
          if (originalBasePath == prevOriginalBasePath) originalBasePath = '';
          fieldPath = fieldPath.substr(1);
        }
        if (!_.startsWith(fieldPath, '/')) {
          fieldPath =
            '/' +
            ((slugValueBasePath && slugValueBasePath + '.') || '') +
            fieldPath;
        }
        if (_.startsWith(fieldPath, '/' + originalBasePath))
          fieldPath = fieldPath.replace(
            '/' + originalBasePath,
            '/' + slugValueBasePath
          );
        return fieldPath;
      }
      let unwoundFields = slug.fields.map(unwindFieldPath);
      let unwoundGroupPaths = (slug.uniqueGroupFields || []).map(
        unwindFieldPath
      );
      if (
        _.some(unwoundFields.concat(unwoundGroupPaths), path => {
          return docIsModified(doc, path.replace(/^\//, ''));
        })
      ) {
        let s = _.cloneDeep(slug);
        s.path = slugPath;
        s.basePath = unwoundBasePath;
        s.fields = unwoundFields;
        s.uniqueGroupFields = unwoundGroupPaths;
        unwoundSlugs.push(s);
      }
    });
  });
  return unwoundSlugs;
}
 
function unwindPath(doc, path, restPathParts) {
  if (restPathParts === undefined) {
    restPathParts = path.split('.$.');
    path = restPathParts[0];
    restPathParts = _.drop(restPathParts);
  }
 
  let res = [];
  let value = docGet(doc, path);
 
  if (_.isArray(value)) {
    for (let i = 0; i < value.length; i++) {
      let childPath = path + '.' + i + '.' + restPathParts[0];
      res = res.concat(unwindPath(doc, childPath, _.drop(restPathParts)));
    }
  } else {
    if (!restPathParts || !restPathParts.length) res.push(path);
  }
  return res;
}
 
async function setSlugs(doc, slugs, options, findOne, cache) {
  // let slugsMdfPaths = _(slugs)
  //   .map('path')
  //   .zipObject(_.fill(Array(_.size(slugs)), ''))
  //   .value();
  // console.log("slugsMdfPaths",slugsMdfPaths);
  await Promise.all(
    slugs.map(async slug => {
      var fields = [];
 
      slug.fields.forEach(slugField => {
        fields.push(docGet(doc, slugField.replace(/^\//, '')));
      });
      let oldSlug = docGet(doc, slug.path);
      if (
        !(slug.unique || slug.uniqueSlug) &&
        (!slug.uniqueGroupFields || !slug.uniqueGroupFields.length)
      ) {
        if (!oldSlug || !slug.permanent) {
          docSet(doc, slug.path, makeSlug(fields, options));
        }
        return;
      } else {
        var query = {};
        Eif (slug.uniqueGroupFields) {
          slug.uniqueGroupFields.forEach(function(fieldName) {
            fieldName = fieldName.replace(/^\//, '');
            query[fieldName] = docGet(doc, fieldName);
          });
        }
        Eif (!docGet(doc,slug.path) || !slug.permanent) {
          if (slug.isShortIdMode) {
            docSet(
              doc,
              slug.path,
              await makeUniqueShortIdSlug(
                doc,
                slug.path,
                fields,
                options,
                query,
                findOne,
                slug.forceShortId,
                cache,
                //slugsMdfPaths
              )
            );
          } else {
            docSet(
              doc,
              slug.path,
              await makeUniqueCounterSlug(
                doc,
                slug.path,
                fields,
                options,
                slug.padding,
                query,
                findOne,
                cache,
                //slugsMdfPaths
              )
            );
          }
        }
      }
    })
  );
  return doc;
}
 
function makeSlug(values, options) {
  var slug = getSlug(values.join(' '), options);
 
  return slug;
}
function extractCounter(value, separator) {
  let count = 0,
    test = new RegExp(separator + '(\\d+)$'),
    match = null;
 
  if ((match = value.match(test))) {
    count = match[1];
  }
  return parseInt(count);
}
 
async function makeUniqueCounterSlug(
  doc,
  path,
  values,
  options,
  padding,
  groups,
  findOne,
  cache,
  //slugsMdfPaths
) {
  let slug = makeSlug(values, options);
  let originalSlug = slug;
  let count = 0;
 
  let result = await findSame(
    cache,
    doc,
    groups,
    path,
    slug,
    true,
    options,
    findOne,
    //slugsMdfPaths
  );
  if (result) {
    count = extractCounter(result, options.separator) + 1;
    slug += options.separator + _.padStart(count, padding, '0');
  }
  updateUpdCache(cache, path, originalSlug, slug);
  // console.log('after cache', cache);
  return slug;
}
 
async function makeUniqueShortIdSlug(
  doc,
  path,
  values,
  options,
  groups,
  findOne,
  forceShortId,
  cache,
  //slugsMdfPaths
) {
  let slug = makeSlug(values, options);
  let originalSlug = slug;
 
  let result = await findSame(
    cache,
    doc,
    groups,
    path,
    slug,
    false,
    options,
    findOne,
    //slugsMdfPaths
  );
  if (result) {
    // console.log(`slug already exists at ${path}`, result);
    let oldSlug = docGet(doc, path);
    if (
      //reuse old slug if possible
      oldSlug &&
      oldSlug.match(new RegExp('^' + slug + options.separator + '.*$'))
    ) {
      // console.log("reuse old random slug",doc[path]);
      slug = oldSlug;
    } else slug += options.separator + shortId.generate();
  } else {
    if (forceShortId) {
      slug += options.separator + shortId.generate();
    }
  }
  updateUpdCache(cache, path, originalSlug, slug);
  // console.log('after cache', cache);
  return slug;
}