Use hash instead of random for default index name (#9448)

* [Fix]: Use hash instead of random for default index name

* Move hash function to separate util file

* Reduce max size of index name to 60 from 64

Co-authored-by: rijkvanzanten <rijkvanzanten@me.com>
This commit is contained in:
Farid Saud
2021-11-04 16:37:03 -05:00
committed by GitHub
parent 42512b8874
commit 493a35da90
2 changed files with 18 additions and 7 deletions

View File

@@ -1,6 +1,4 @@
import { customAlphabet } from 'nanoid';
const generateID = customAlphabet('abcdefghijklmnopqrstuvxyz', 5);
import { simpleHash } from './get-simple-hash';
/**
* Generate an index name for a given collection + fields combination.
@@ -20,10 +18,10 @@ export function getDefaultIndexName(
const table = collection.replace(/\.|-/g, '_');
const indexName = (table + '_' + fields.join('_') + '_' + type).toLowerCase();
if (indexName.length <= 64) return indexName;
if (indexName.length <= 60) return indexName;
const suffix = `__${generateID()}_${type}`;
const prefix = indexName.substring(0, 64 - suffix.length);
const suffix = `__${simpleHash(indexName)}_${type}`;
const prefix = indexName.substring(0, 60 - suffix.length);
return `${prefix}__${generateID()}_${type}`;
return `${prefix}${suffix}`;
}

View File

@@ -0,0 +1,13 @@
/**
* Generate a simple short hash for a given string
* This is not cryptographically secure in any way, and has a high chance of collision
*/
export function simpleHash(str: string) {
let hash = 0;
for (let i = 0; i < str.length; hash &= hash) {
hash = 31 * hash + str.charCodeAt(i++);
}
return hash.toString(16);
}