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

[legacy-framework] Subtemplate management #2134

Closed
Closed
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
21 changes: 20 additions & 1 deletion packages/generator/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,11 @@ export abstract class Generator<
private useTs: boolean
private prettier: typeof import("prettier") | undefined

// relative path to templates folder of Generators implementation folder
static sourceRootFromTemplate(template: string): string {
return path.join(__dirname, "../templates", template)
}

prettierDisabled: boolean = false
unsafe_disableConflictChecker = false
returnResults: boolean = false
Expand All @@ -136,7 +141,6 @@ export abstract class Generator<

constructor(protected readonly options: T) {
super()

this.options = options
this.store = createStore()
this.fs = createEditor(this.store)
Expand Down Expand Up @@ -199,6 +203,21 @@ export abstract class Generator<
if (codeFileExtensions.test(pathEnding)) {
templatedFile = this.replaceConditionals(inputStr, templateValues, prettierOptions || {})
}
// templatedFile.match
const fieldTemplateRegExp = new RegExp(/{?\/\* template: (.*) \*\/}?/)
const fieldTemplateString = templatedFile
.match(fieldTemplateRegExp)?.[0]
.replace(fieldTemplateRegExp, "$1")
if (fieldTemplateString) {
const fieldTemplatePosition = templatedFile.search(fieldTemplateRegExp)
templatedFile = [
templatedFile.slice(0, fieldTemplatePosition),
...(templateValues.fieldTemplateValues?.map((values: any) =>
this.replaceTemplateValues(fieldTemplateString, values),
) || []),
templatedFile.slice(fieldTemplatePosition),
].join("\n")
}
templatedFile = this.replaceTemplateValues(templatedFile, templateValues)
if (!this.useTs && tsExtension.test(pathEnding)) {
return (
Expand Down
4 changes: 2 additions & 2 deletions packages/generator/src/generators/app-generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import {log} from "@blitzjs/display"
import chalk from "chalk"
import spawn from "cross-spawn"
import {readJSONSync, writeJson} from "fs-extra"
import {join, resolve} from "path"
import {join} from "path"
import username from "username"
import {Generator, GeneratorOptions} from "../generator"
import {fetchLatestVersionsFor} from "../utils/fetch-latest-version-for"
Expand All @@ -24,7 +24,7 @@ export interface AppGeneratorOptions extends GeneratorOptions {
}

export class AppGenerator extends Generator<AppGeneratorOptions> {
sourceRoot: string = resolve(__dirname, "./templates/app")
sourceRoot: string = Generator.sourceRootFromTemplate("app")
// Disable file-level prettier because we manually run prettier at the end
prettierDisabled = true
packageInstallSuccess: boolean = false
Expand Down
13 changes: 10 additions & 3 deletions packages/generator/src/generators/form-generator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {join} from "path"
import {Generator, GeneratorOptions} from "../generator"
import {camelCaseToKebabCase} from "../utils/inflector"
import {camelCaseToKebabCase, singleCamel, singlePascal} from "../utils/inflector"

export interface FormGeneratorOptions extends GeneratorOptions {
ModelName: string
Expand All @@ -11,11 +10,12 @@ export interface FormGeneratorOptions extends GeneratorOptions {
parentModels?: string
ParentModel?: string
ParentModels?: string
extraArgs?: string[]
}

export class FormGenerator extends Generator<FormGeneratorOptions> {
static subdirectory = "queries"
sourceRoot = join(__dirname, "./templates/form")
sourceRoot = Generator.sourceRootFromTemplate("form")

private getId(input: string = "") {
if (!input) return input
Expand All @@ -42,6 +42,13 @@ export class FormGenerator extends Generator<FormGeneratorOptions> {
modelNames: this.options.modelNames,
ModelName: this.options.ModelName,
ModelNames: this.options.ModelNames,
fieldTemplateValues: this.options.extraArgs?.map((arg: string) => {
const [valueName] = arg.split(":")
return {
fieldName: singleCamel(valueName),
FieldName: singlePascal(valueName).replace(/(?!^)([A-Z])/g, " $1"),
Comment on lines +48 to +49
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Also add the following which will put spaces between the words.

  • field_name
  • Field_name
  • Field_Name - ex: myFirstName -> My First Name

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Still todo

}
}),
}
}

Expand Down
3 changes: 1 addition & 2 deletions packages/generator/src/generators/mutation-generator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import {join} from "path"
import {Generator, GeneratorOptions} from "../generator"
import {camelCaseToKebabCase} from "../utils/inflector"

Expand All @@ -9,7 +8,7 @@ export interface MutationGeneratorOptions extends GeneratorOptions {

export class MutationGenerator extends Generator<MutationGeneratorOptions> {
static subdirectory = "mutation"
sourceRoot = join(__dirname, "./templates/mutation")
sourceRoot = Generator.sourceRootFromTemplate("mutation")

// eslint-disable-next-line require-await
async getTemplateValues() {
Expand Down
21 changes: 18 additions & 3 deletions packages/generator/src/generators/mutations-generator.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import {join} from "path"
import {Generator, GeneratorOptions} from "../generator"
import {camelCaseToKebabCase} from "../utils/inflector"
import {camelCaseToKebabCase, singleCamel} from "../utils/inflector"

export interface MutationsGeneratorOptions extends GeneratorOptions {
ModelName: string
Expand All @@ -11,11 +10,12 @@ export interface MutationsGeneratorOptions extends GeneratorOptions {
parentModels?: string
ParentModel?: string
ParentModels?: string
extraArgs?: string[]
}

export class MutationsGenerator extends Generator<MutationsGeneratorOptions> {
static subdirectory = "mutations"
sourceRoot = join(__dirname, "./templates/mutations")
sourceRoot = Generator.sourceRootFromTemplate("mutations")

private getId(input: string = "") {
if (!input) return input
Expand All @@ -27,6 +27,14 @@ export class MutationsGenerator extends Generator<MutationsGeneratorOptions> {
return `[${input}]`
}

private getZodTypeName(type: string = "") {
if (["string", "null", "undefined", "unknown", "void", "boolean"].includes(type)) {
return type
} else {
return type === "int" ? "number" : "any"
}
}

// eslint-disable-next-line require-await
async getTemplateValues() {
return {
Expand All @@ -42,6 +50,13 @@ export class MutationsGenerator extends Generator<MutationsGeneratorOptions> {
modelNames: this.options.modelNames,
ModelName: this.options.ModelName,
ModelNames: this.options.ModelNames,
fieldTemplateValues: this.options.extraArgs?.map((arg: string) => {
const [valueName, typeName] = arg.split(":")
return {
attributeName: singleCamel(valueName),
zodTypeName: this.getZodTypeName(typeName),
}
}),
}
}

Expand Down
3 changes: 1 addition & 2 deletions packages/generator/src/generators/page-generator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import {join} from "path"
import {Generator, GeneratorOptions} from "../generator"
import {camelCaseToKebabCase} from "../utils/inflector"

Expand All @@ -15,7 +14,7 @@ export interface PageGeneratorOptions extends GeneratorOptions {

export class PageGenerator extends Generator<PageGeneratorOptions> {
static subdirectory = "pages"
sourceRoot = join(__dirname, "./templates/page")
sourceRoot = Generator.sourceRootFromTemplate("page")

private getId(input: string = "") {
if (!input) return input
Expand Down
3 changes: 1 addition & 2 deletions packages/generator/src/generators/queries-generator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import {join} from "path"
import {Generator, GeneratorOptions} from "../generator"
import {camelCaseToKebabCase} from "../utils/inflector"

Expand All @@ -15,7 +14,7 @@ export interface QueriesGeneratorOptions extends GeneratorOptions {

export class QueriesGenerator extends Generator<QueriesGeneratorOptions> {
static subdirectory = "queries"
sourceRoot = join(__dirname, "./templates/queries")
sourceRoot = Generator.sourceRootFromTemplate("queries")

private getId(input: string = "") {
if (!input) return input
Expand Down
3 changes: 1 addition & 2 deletions packages/generator/src/generators/query-generator.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import {join} from "path"
import {Generator, GeneratorOptions} from "../generator"
import {camelCaseToKebabCase} from "../utils/inflector"

Expand All @@ -9,7 +8,7 @@ export interface QueryGeneratorOptions extends GeneratorOptions {

export class QueryGenerator extends Generator<QueryGeneratorOptions> {
static subdirectory = "query"
sourceRoot = join(__dirname, "./templates/query")
sourceRoot = Generator.sourceRootFromTemplate("query")

// eslint-disable-next-line require-await
async getTemplateValues() {
Expand Down
2 changes: 1 addition & 1 deletion packages/generator/templates/form/__ModelName__Form.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export {FORM_ERROR} from "app/core/components/Form"
export function __ModelName__Form<S extends z.ZodType<any, any>>(props: FormProps<S>) {
return (
<Form<S> {...props}>
<LabeledTextField name="name" label="Name" placeholder="Name" />
{/* fieldTemplate: <LabeledTextField name="__fieldName__" label="__FieldName__" placeholder="__FieldName__" /> */}
</Form>
)
}
Expand Down
8 changes: 4 additions & 4 deletions packages/generator/templates/mutations/create__ModelName__.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import {resolver} from "blitz"
import { resolver } from "blitz"
import db from "db"
import * as z from "zod"

if (process.env.parentModel) {
const Create__ModelName__ = z.object({
name: z.string(),
/* fieldTemplate: __fieldName__: z.__zodType__(), */
__parentModelId__: z.number()
}).nonstrict()
} else {
const Create__ModelName__ = z.object({
name: z.string(),
/* fieldTemplate: __fieldName__: z.__zodType__(), */
}).nonstrict()
}

Expand All @@ -18,7 +18,7 @@ export default resolver.pipe(
resolver.authorize(),
async (input) => {
// TODO: in multi-tenant app, you must add validation to ensure correct tenant
const __modelName__ = await db.__modelName__.create({data: input})
const __modelName__ = await db.__modelName__.create({ data: input })

return __modelName__
},
Expand Down
8 changes: 4 additions & 4 deletions packages/generator/templates/mutations/update__ModelName__.ts
Original file line number Diff line number Diff line change
@@ -1,18 +1,18 @@
import {resolver} from "blitz"
import { resolver } from "blitz"
import db from "db"
import * as z from "zod"

const Update__ModelName__ = z.object({
id: z.number(),
name: z.string(),
/* fieldTemplate: __fieldName__: z.__zodType__(), */
}).nonstrict()

export default resolver.pipe(
resolver.zod(Update__ModelName__),
resolver.authorize(),
async ({id, ... data}) => {
async ({ id, ...data }) => {
// TODO: in multi-tenant app, you must add validation to ensure correct tenant
const __modelName__ = await db.__modelName__.update({where: {id}, data})
const __modelName__ = await db.__modelName__.update({ where: { id }, data })

return __modelName__
},
Expand Down