stitch-ui
Version:
86 lines (73 loc) • 2.48 kB
JavaScript
const DISALLOWED_NS_CHARS = ["/", "\\", ".", "\u0000", "$"];
const DISALLOWED_NS_COLLECTION_CHARS = ["/", "\\", "\u0000", "$"];
const DISALLOWED_FIELD_CHARS = ["$", "\u0000"];
const INVALID_DB_NAMES = ["system", "local", "admin"];
// Returns false if the string contains any of the set of characters
// not allowed in DB or collection names.
export const validateDisallowedChars = (s, disallowedCharSet) =>
!disallowedCharSet.some(illegalChar => s.indexOf(illegalChar) >= 0);
export const validateCollectionName = cName => {
if (cName.length === 0) {
return "Collection name cannot be blank";
}
if (cName.indexOf("system.") === 0) {
return "Collection names may not be prefixed with 'system.'";
}
if (cName[0] === ".") {
return `Collection names may not start with '.'`;
}
if (!validateDisallowedChars(cName, DISALLOWED_NS_COLLECTION_CHARS)) {
return "Collection name contains illegal characters";
}
return null;
};
// TODO perform this validation on the backend.
export const validateDBName = dbName => {
if (dbName.length === 0) {
return "Database name must not be empty";
}
if (dbName.length > 63) {
return "Database name is too long";
}
if (INVALID_DB_NAMES.includes(dbName)) {
return `Database name may not be '${dbName}'`;
}
if (!validateDisallowedChars(dbName, DISALLOWED_NS_CHARS)) {
return "Database name contains illegal characters";
}
return null;
};
export const validateNamespace = n => {
if (n.length > 122) {
return "Namespace is too long.";
}
// find the first instance of "." in the namespace
const firstDotIndex = n.indexOf(".");
if (firstDotIndex === 0) {
return "Namespace cannot begin with '.'";
} else if (firstDotIndex === n.length - 1) {
return "Namespace cannot end with '.'";
} else if (firstDotIndex < 0) {
return "Namespace must contain a '.' to separate database and collection.";
}
const dbName = n.substring(0, firstDotIndex);
const collectionName = n.substring(firstDotIndex + 1);
const dbErr = validateDBName(dbName);
if (dbErr) {
return dbErr;
}
const cErr = validateCollectionName(collectionName);
if (cErr) {
return cErr;
}
return null;
};
export const validateFieldName = fName => {
if (fName.length === 0) {
return "Field name may not be empty.";
}
if (!validateDisallowedChars(fName, DISALLOWED_FIELD_CHARS)) {
return "Field name contains illegal characters";
}
return null;
};