Skip to content

Commit

Permalink
Show an error if a reserved word is used for blitz generate's model…
Browse files Browse the repository at this point in the history
… name (#2813)

(patch)
  • Loading branch information
namirsab authored Oct 8, 2021
1 parent baeefff commit 3473cec
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 0 deletions.
10 changes: 10 additions & 0 deletions packages/cli/src/commands/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -208,6 +208,15 @@ export class Generate extends Command {
}
}

validateModelName(modelName: string): void {
const RESERVED_MODEL_NAMES = ["page", "api", "query", "mutation"]
if (RESERVED_MODEL_NAMES.includes(modelName)) {
throw new Error(
`Names ${RESERVED_MODEL_NAMES} or their plurals cannot be used as model names`,
)
}
}

async run() {
const {args, argv, flags}: {args: Args; argv: string[]; flags: Flags} = this.parse(Generate)
debug("args: ", args)
Expand All @@ -218,6 +227,7 @@ export class Generate extends Command {
try {
const {model, context} = this.getModelNameAndContext(args.model, flags.context)
const singularRootContext = modelName(model)
this.validateModelName(singularRootContext)

const generators = generatorMap[args.type]
for (const GeneratorClass of generators) {
Expand Down
35 changes: 35 additions & 0 deletions packages/cli/test/commands/generate.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,4 +48,39 @@ describe("`generate` command", () => {
})
})
})

describe("#validateModelName", () => {
describe("when model name is not reserved", () => {
it("should do nothing", () => {
const validateModelName = Generate.prototype.validateModelName
expect(() => validateModelName("project")).not.toThrow()
})
})
describe("when model name is reserved", () => {
it('should throw an error for model "page"', () => {
const getModelNameAndContext = Generate.prototype.validateModelName
expect(() => getModelNameAndContext("page")).toThrowError(
"Names page,api,query,mutation or their plurals cannot be used as model names",
)
})
it('should throw an error for model "api"', () => {
const getModelNameAndContext = Generate.prototype.validateModelName
expect(() => getModelNameAndContext("api")).toThrowError(
"Names page,api,query,mutation or their plurals cannot be used as model names",
)
})
it('should throw an error for model "query"', () => {
const getModelNameAndContext = Generate.prototype.validateModelName
expect(() => getModelNameAndContext("query")).toThrowError(
"Names page,api,query,mutation or their plurals cannot be used as model names",
)
})
it('should throw an error for model "mutation"', () => {
const getModelNameAndContext = Generate.prototype.validateModelName
expect(() => getModelNameAndContext("mutation")).toThrowError(
"Names page,api,query,mutation or their plurals cannot be used as model names",
)
})
})
})
})

0 comments on commit 3473cec

Please sign in to comment.