From 493a35da906da7342d9aa87310db00be6eba959e Mon Sep 17 00:00:00 2001 From: Farid Saud Date: Thu, 4 Nov 2021 16:37:03 -0500 Subject: [PATCH] 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 --- api/src/utils/get-default-index-name.ts | 12 +++++------- api/src/utils/get-simple-hash.ts | 13 +++++++++++++ 2 files changed, 18 insertions(+), 7 deletions(-) create mode 100644 api/src/utils/get-simple-hash.ts diff --git a/api/src/utils/get-default-index-name.ts b/api/src/utils/get-default-index-name.ts index 2c6e94cf38..b9a70fc9cf 100644 --- a/api/src/utils/get-default-index-name.ts +++ b/api/src/utils/get-default-index-name.ts @@ -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}`; } diff --git a/api/src/utils/get-simple-hash.ts b/api/src/utils/get-simple-hash.ts new file mode 100644 index 0000000000..29c172ee91 --- /dev/null +++ b/api/src/utils/get-simple-hash.ts @@ -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); +}