Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add custom string index support #454

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/metadata.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
'use strict';

const { getKindMetadata } = require('./kinds.js');
const { isStringIndex } = require('./util.js');

const errPrefix = 'Field';
const OPTIONS = ['validate', 'parse', 'serialize', 'format'];
Expand Down Expand Up @@ -61,7 +62,8 @@ class Options {
class Indexes {
extract(key, field) {
const { index, primary, unique, many } = field;
const isIndex = Array.isArray(index || primary || unique);
const chosenIndex = index || primary || unique;
const isIndex = Array.isArray(chosenIndex) || isStringIndex(chosenIndex);
if (isIndex || many) this[key] = field;
return isIndex;
}
Expand Down
15 changes: 14 additions & 1 deletion lib/util.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
'use strict';

const { isFirstLetter } = require('metautil');
const { isFirstLetter, validateBracketBalance } = require('metautil');

const formatters = {
type: (type, req = true) => {
Expand Down Expand Up @@ -41,9 +41,22 @@ const firstKey = (obj) => Object.keys(obj).find(isFirstLetter);

const isInstanceOf = (obj, constrName) => obj?.constructor?.name === constrName;

const isStringIndex = (index) => {
if (typeof index !== 'string') return false;
const brackets = ['(', ')'];
if (brackets.some((bracket) => index.indexOf(bracket) === -1)) return false;
if (!validateBracketBalance(index, brackets.join(''))) return false;
const expression = index.substring(
index.indexOf(brackets[0]) + 1,
index.lastIndexOf(brackets[1]),
);
return expression.trim().length !== 0;
};

module.exports = {
formatters,
checks,
firstKey,
isInstanceOf,
isStringIndex,
};