Created
September 10, 2021 03:52
-
-
Save minhntm/6baf9154e967ef90831a56057832bc5e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface PermissionCondition {} | |
@Entity("permissions") | |
export class Permission extends BaseEntity { | |
// define class attributes... | |
/** | |
* @param condition: {"departmentId": "${id}"} | |
* @param variables: {"id: 1"} | |
* @return condition after parse: {"departmentId": 1} | |
*/ | |
public static parseCondition(condition: PermissionCondition, variables: Record<string, any>): PermissionCondition { | |
if (!condition) return null; | |
const parsedCondition = {}; | |
for (const [key, rawValue] of Object.entries(condition)) { | |
if (rawValue !== null && typeof rawValue === "object") { | |
const value = this.parseCondition(rawValue, variables); | |
parsedCondition[key] = value; | |
continue; | |
} | |
if (typeof rawValue !== "string") { | |
parsedCondition[key] = rawValue; | |
continue; | |
} | |
// find placeholder "${}"" | |
const matches = /^\\${([a-zA-Z0-9]+)}$/.exec(rawValue); | |
if (!matches) { | |
parsedCondition[key] = rawValue; | |
continue; | |
} | |
const value = variables[matches[1]]; | |
if (typeof value === "undefined") { | |
throw new ReferenceError(`Variable ${name} is not defined`); | |
} | |
parsedCondition[key] = value; | |
} | |
return parsedCondition; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment