adelsz / pgtyped

pgTyped - Typesafe SQL in TypeScript
https://pgtyped.dev
MIT License
2.91k stars 94 forks source link

typesOverrides converts relative paths in possibly undesirable ways #564

Open SebastienGllmt opened 7 months ago

SebastienGllmt commented 7 months ago

Describe the bug

In my project, I have an enum that is common between all my different generated files. Ideally pgtyped would be smart enough to detect this is the same enum in all files and place it in some kind common file, but this isn't supported so I want to have a workaround myself with a custom common.ts

"typesOverrides": {
    "lobby_status": "./common.js#LobbyStatus"
}

for reference, this is my enum in sql

CREATE TYPE lobby_status AS ENUM ('open', 'active', 'finished', 'closed');

Expected behavior

The generated code by `pgtyped becomes

import type { LobbyStatus } from './common.js';

Behavior seen

Paths that start with a . are turned into relative imports here, so instead the generated code becomes

import type { LobbyStatus } from '../../common.js';

Which gives an error since this path doesn't exist

Workaround

As a workaround to this, I modified my tsconfig to use

"compilerOptions": {
    "paths": {
      "@src/*": [
        "./src/*"
      ],
    }
  },

and then updated my pgtyped config to be

"typesOverrides": {
    "lobby_status": "@src/common.js#LobbyStatus"
  }

So now it's no longer a relative import and the generated code works as expected. This workaround does come with some unfortunate trade-offs though:

  1. It makes that your project build output contains a @src import, making it harder to compose with other libraries unless you add an extra compilation step to remove this @src from your build output with tsc-alias (or a more heavy-handed approach like webpack)
  2. Other issues mentioned in #565

Fixes

Given the context, I see 3 ways to solve this issue:

  1. Solve the underlying issue (#565)
  2. Change the relative path transformation of typesOverrides that start with .. Given this would be a breaking change and it's not clear this wouldn't introduce new issues instead, this may not be the right option
  3. Mention the workaround I came up with in the docs for others that have the same constraints. It's not a great solution long-term though for the reasons mentioned