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

fix: Allow overriding moduleResolution #30

Merged
merged 9 commits into from
Jan 27, 2024
Merged
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
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,11 @@ In addition to the Prisma features, you can also generate Drizzle-specific featu
| output | Change the output | "./drizzle" | "../models" |
| formatter | Run prettier after generation | - | "prettier" |
| relationalQuery | Flag to generate relational query | true | false |
| moduleResolution | Specify the [module resolution](https://www.typescriptlang.org/tsconfig#moduleResolution) that will affect the import style | _*auto_ | nodenext |
| verbose | Flag to enable verbose logging | - | true |

_* It will find the closest tsconfig from the current working directory. Note that [extends](https://www.typescriptlang.org/tsconfig#extends) is not supported_

### Setting up [relational query](https://orm.drizzle.team/docs/rqb)

```ts
Expand Down Expand Up @@ -187,3 +190,12 @@ export const users = pgTable('User', {
...
})
```
## Gotchas
### Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'.

By default, the generator will try to find the closest tsconfig from the current working directory to determine the import style, whether to add `.js` or not. When there's no config found, it will use the common import (e.g. `import { users } from './users'`).

You can explicitly set the `moduleResolution` option in the [generator configuration](#configuration).

Check also [the discussion](https://github.com/farreldarian/prisma-generator-drizzle/issues/18)

12 changes: 12 additions & 0 deletions packages/generator/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,8 +68,11 @@ In addition to the Prisma features, you can also generate Drizzle-specific featu
| output | Change the output | "./drizzle" | "../models" |
| formatter | Run prettier after generation | - | "prettier" |
| relationalQuery | Flag to generate relational query | true | false |
| moduleResolution | Specify the [module resolution](https://www.typescriptlang.org/tsconfig#moduleResolution) that will affect the import style | _*auto_ | nodenext |
| verbose | Flag to enable verbose logging | - | true |

_* It will find the closest tsconfig from the current working directory. Note that [extends](https://www.typescriptlang.org/tsconfig#extends) is not supported_

### Setting up [relational query](https://orm.drizzle.team/docs/rqb)

```ts
Expand Down Expand Up @@ -187,3 +190,12 @@ export const users = pgTable('User', {
...
})
```
## Gotchas
### Relative import paths need explicit file extensions in ECMAScript imports when '--moduleResolution' is 'node16' or 'nodenext'.

By default, the generator will try to find the closest tsconfig from the current working directory to determine the import style, whether to add `.js` or not. When there's no config found, it will use the common import (e.g. `import { users } from './users'`).

You can explicitly set the `moduleResolution` option in the [generator configuration](#configuration).

Check also [the discussion](https://github.com/farreldarian/prisma-generator-drizzle/issues/18)

47 changes: 27 additions & 20 deletions packages/generator/src/generator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,14 @@ import {
createModelModule,
ModelModule,
} from './lib/adapter/modules/createModelModule'
import { mysqlAdapter } from './lib/adapter/providers/mysql'
import { postgresAdapter } from './lib/adapter/providers/postgres'
import { sqliteAdapter } from './lib/adapter/providers/sqlite'
import { isRelationalQueryEnabled } from './lib/config'
import { Context } from './lib/context'
import { logger } from './lib/logger'
import { getEnumModuleName } from './lib/prisma-helpers/enums'
import { isRelationField } from './lib/prisma-helpers/field'
import { ImportValue, namedImport, NamedImport } from './lib/syntaxes/imports'
import { createModule, Module } from './lib/syntaxes/module'
import { setGeneratorContext } from './shared/generator-context'

const { version } = require('../package.json')

Expand All @@ -39,6 +37,7 @@ generatorHandler({
}
},
onGenerate: async (options: GeneratorOptions) => {
setGeneratorContext(options)
logger.applyConfig(options)

logger.log('Generating drizzle schema...')
Expand All @@ -48,7 +47,7 @@ generatorHandler({
if (options.datasources.length > 1)
throw new Error('Only one datasource is supported')

const adapter = getAdapter(options)
const adapter = await getAdapter(options)
const ctx: Context = {
adapter,
config: options.generator.config,
Expand Down Expand Up @@ -189,23 +188,31 @@ function writeModule(basePath: string, module: Module) {
fs.writeFileSync(writeLocation, module.code)
}

function getAdapter(options: GeneratorOptions) {
return (() => {
switch (options.datasources[0].provider) {
case 'cockroachdb': // CockroahDB should be postgres compatible
case 'postgres':
case 'postgresql':
return postgresAdapter
case 'mysql':
return mysqlAdapter
case 'sqlite':
return sqliteAdapter
default:
throw new Error(
`Connector ${options.datasources[0].provider} is not supported`
)
/**
* @dev Importing the adapter dynamically so `getGeneratorContext()` won't
* be called before initialization (`onGenerate`)
*/
async function getAdapter(options: GeneratorOptions) {
switch (options.datasources[0].provider) {
case 'cockroachdb': // CockroahDB should be postgres compatible
case 'postgres':
case 'postgresql': {
const mod = await import('./lib/adapter/providers/postgres')
return mod.postgresAdapter
}
})()
case 'mysql': {
const mod = await import('./lib/adapter/providers/mysql')
return mod.mysqlAdapter
}
case 'sqlite': {
const mod = await import('./lib/adapter/providers/sqlite')
return mod.sqliteAdapter
}
default:
throw new Error(
`Connector ${options.datasources[0].provider} is not supported`
)
}
}

function deduplicateModels(accum: DMMF.Model[], model: DMMF.Model) {
Expand Down
6 changes: 6 additions & 0 deletions packages/generator/src/lib/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,3 +7,9 @@ export function isRelationalQueryEnabled(config: Config) {
if (value === 'false') return false
return true
}

export function getModuleResolution(config: Config) {
if ('moduleResolution' in config) {
return config.moduleResolution
}
}
11 changes: 5 additions & 6 deletions packages/generator/src/lib/syntaxes/imports.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { getGeneratorContext } from '~/shared/generatorContext'
import { getGeneratorContext } from '~/shared/generator-context'

export function namedImport(names: string[], path: string) {
return {
Expand Down Expand Up @@ -38,14 +38,13 @@ export type ImportValue =
| ReturnType<typeof defaultImportValue>
| ReturnType<typeof wildcardImport>

const isNodeNext =
getGeneratorContext().moduleResolution.toLowerCase() !== 'nodenext'

/**
* Adds the .js extension to relative imports.
*/
function renderImportPath(path: string) {
if (isNodeNext) return path
if (getGeneratorContext().moduleResolution?.toLowerCase() === 'nodenext') {
return path.startsWith('.') ? `${path}.js` : path
}

return path.startsWith('.') ? `${path}.js` : path
return path
}
45 changes: 45 additions & 0 deletions packages/generator/src/shared/generator-context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
import path from 'path'
import fs from 'fs'
import { GeneratorOptions } from '@prisma/generator-helper'
import { getModuleResolution } from '~/lib/config'

type GeneratorContext = {
moduleResolution?: string
}

let generatorContext_: GeneratorContext | undefined

export function setGeneratorContext(options: GeneratorOptions) {
generatorContext_ = {
moduleResolution: resolveModuleResolution(options),
}
}

export function getGeneratorContext() {
if (generatorContext_ == null) {
throw new Error('Generator context not set')
}

return generatorContext_
}

function resolveModuleResolution(options: GeneratorOptions) {
const specified = getModuleResolution(options.generator.config)
if (specified) return specified

const tsConfigPath = findTsConfig()
if (!tsConfigPath) return

const tsConfig = JSON.parse(fs.readFileSync(tsConfigPath, 'utf-8'))
return tsConfig?.compilerOptions?.moduleResolution
}

function findTsConfig() {
let projectDir = process.cwd()
while (projectDir !== '/') {
const tsConfigPath = path.join(projectDir, 'tsconfig.json')
if (fs.existsSync(tsConfigPath)) return tsConfigPath

projectDir = path.join(projectDir, '..')
}
}
34 changes: 0 additions & 34 deletions packages/generator/src/shared/generatorContext.ts

This file was deleted.

Loading