Skip to content

Commit

Permalink
Support including tables with RegExp
Browse files Browse the repository at this point in the history
  • Loading branch information
TonyGravagno committed Jul 11, 2023
1 parent 266f9f0 commit 9c0de7a
Show file tree
Hide file tree
Showing 6 changed files with 78 additions and 32 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,5 @@
node_modules
pnpm-lock.yaml
package-lock.json
mysql-zod.json
.vscode
10 changes: 5 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -83,8 +83,8 @@ await generate({
"user": "root",
"password": "secret",
"database": "myapp",
"tables": ["user", "log"],
"ignore": ["log"],
"tables": ["user", "log", "/^prod(1|2)_/"],
"ignore": ["log", "/^temp/"],
"folder": "@zod",
"suffix": "table",
"camelCase": false,
Expand All @@ -95,10 +95,10 @@ await generate({

| Option | Description |
| ------ | ----------- |
| tables | Filter the tables to include only those specified. |
| ignore | Filter the tables to exclude those specified. |
| tables | Filter the tables to include only those specified. If a table name begins and ends with "/", it will be processed as a regular expression. |
| ignore | Filter the tables to exclude those specified. If a table name begins and ends with "/", it will be processed as a regular expression. |
| folder | Specify the output directory. |
| suffix | Suffix to the name of a generated file. (eg: `user.table.ts`) |
| camelCase | Convert all table names and their properties to camelcase. (eg: `profile_picture` becomes `profilePicture`) |
| nullish | Set schema as `nullish` instead of `nullable` |
| requiredString | Add `min(1)` for string schema |
| requiredString | Add `min(1)` for string schema |
10 changes: 5 additions & 5 deletions dist/main.js

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,9 @@
],
"scripts": {
"build": "esbuild src/main.ts --format=esm --platform=node --outfile=dist/main.js --minify && esbuild src/bin.ts --format=esm --platform=node --outfile=dist/bin.js --minify",
"build-dts": "tsc src/main.ts -d --emitDeclarationOnly --esModuleInterop --outDir dist"
"build-dts": "tsc src/main.ts -d --emitDeclarationOnly --esModuleInterop --outDir dist",
"lint": "eslint .",
"lint:fix": "eslint . --fix"
},
"dependencies": {
"camelcase": "^7.0.1",
Expand Down
81 changes: 61 additions & 20 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,20 @@
/* eslint-disable key-spacing */
/* eslint-disable no-case-declarations */
/* eslint-disable no-multi-spaces */

import path from 'node:path'
import fs from 'fs-extra'
import knex from 'knex'
import camelCase from 'camelcase'

function getType(descType: Desc['Type'], descNull: Desc['Null'], config: Config) {
const isNullish = config.nullish && config.nullish === true
const isNullish = config.nullish && config.nullish === true
const isRequiredString = config.requiredString && config.requiredString === true
const type = descType.split('(')[0].split(' ')[0]
const isNull = descNull === 'YES'
const string = ['z.string()']
const number = ['z.number()']
const nullable = isNullish ? 'nullish()' : 'nullable()'
const nonnegative = 'nonnegative()'
const min1 = 'min(1)'
const type = descType.split('(')[0].split(' ')[0]
const isNull = descNull === 'YES'
const string = ['z.string()']
const number = ['z.number()']
const nullable = isNullish ? 'nullish()' : 'nullable()'
const nonnegative = 'nonnegative()'
const min1 = 'min(1)'
switch (type) {
case 'date':
case 'datetime':
Expand Down Expand Up @@ -59,9 +57,9 @@ export async function generate(config: Config) {
const db = knex({
client: 'mysql2',
connection: {
host : config.host,
port : config.port,
user : config.user,
host: config.host,
port: config.port,
user: config.user,
password: config.password,
database: config.database,
},
Expand All @@ -72,13 +70,56 @@ export async function generate(config: Config) {
const t = await db.raw('SELECT table_name as table_name FROM information_schema.tables WHERE table_schema = ?', [config.database])
let tables = t[0].map((row: any) => row.table_name).filter((table: string) => !table.startsWith('knex_')).sort() as Tables

const includedTables = config.tables
if (includedTables && includedTables.length)
tables = tables.filter(table => includedTables.includes(table))
const allIncludedTables = config.tables
const includedTablesRegex = allIncludedTables?.filter((includeString) => {
const isPattern
= includeString.startsWith('/') && includeString.endsWith('/')
return isPattern
})
const includedTableNames = allIncludedTables?.filter(
table => includedTablesRegex?.includes(table),
)

if (includedTableNames && includedTableNames.length) {
tables = tables.filter((table) => {
if (includedTableNames.includes(table))
return true
let useTable = false
if (includedTablesRegex && includedTablesRegex.length) {
includedTablesRegex.forEach((text) => {
const pattern = text.substring(1, text.length - 1)
if (table.match(pattern) !== null)
useTable = true
})
}
return useTable
})
}

const ignoredTables = config.ignore
if (ignoredTables && ignoredTables.length)
tables = tables.filter(table => !ignoredTables.includes(table))
const allIgnoredTables = config.ignore
const ignoredTablesRegex = allIgnoredTables?.filter((ignoreString) => {
const isPattern
= ignoreString.startsWith('/') && ignoreString.endsWith('/')
return isPattern
})
const ignoredTableNames = allIgnoredTables?.filter(
table => !ignoredTablesRegex?.includes(table),
)

if (ignoredTableNames && ignoredTableNames.length)
tables = tables.filter(table => !ignoredTableNames.includes(table))

if (ignoredTablesRegex && ignoredTablesRegex.length) {
tables = tables.filter((table) => {
let useTable = true
ignoredTablesRegex.forEach((text) => {
const pattern = text.substring(1, text.length - 1)
if (table.match(pattern) !== null)
useTable = false
})
return useTable
})
}

for (let table of tables) {
const d = await db.raw(`DESC ${table}`)
Expand All @@ -99,7 +140,7 @@ export const ${table} = z.object({`
export type ${camelCase(`${table}Type`)} = z.infer<typeof ${table}>
`
const dir = (config.folder && config.folder !== '') ? config.folder : '.'
const dir = (config.folder && config.folder !== '') ? config.folder : '.'
const file = (config.suffix && config.suffix !== '') ? `${table}.${config.suffix}.ts` : `${table}.ts`
const dest = path.join(dir, file)
console.log('Created:', dest)
Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,5 @@
"target": "ESNext",
"lib": ["ESNext"],
"esModuleInterop": true
},
}
}

0 comments on commit 9c0de7a

Please sign in to comment.