rads-db 3.0.84 → 3.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -2,11 +2,11 @@ import fs from "node:fs/promises";
2
2
  import fs2 from "node:fs";
3
3
  import path from "node:path";
4
4
  import _ from "lodash";
5
- import { parseSchema } from "./lib.mjs";
6
- export async function generateClient(options) {
7
- const normalizedOptions = normalizeOptions(options);
8
- console.time("[rads-db] Schema generated in");
9
- const schema = await getSchema(normalizedOptions);
5
+ import { createJiti } from "jiti";
6
+ export async function generateClient() {
7
+ console.time('"node_modules/_rads-db" generated in');
8
+ const config = await loadConfig();
9
+ const schemas = await getSchemas(config);
10
10
  const nodeModulesPath = path.resolve("./node_modules");
11
11
  const radsDbPath = path.join(nodeModulesPath, "./_rads-db");
12
12
  if (!fs2.existsSync(nodeModulesPath)) {
@@ -17,14 +17,15 @@ export async function generateClient(options) {
17
17
  if (!fs2.existsSync(radsDbPath)) {
18
18
  await fs.mkdir(radsDbPath);
19
19
  }
20
+ const schemasOnly = _.mapValues(schemas, (x) => x.schema);
20
21
  const indexJsText = `
21
22
  Object.defineProperty(exports, "__esModule", { value: true });
22
- exports.schema=${JSON.stringify(schema)}
23
+ exports.schemas=${JSON.stringify(schemasOnly)}
23
24
  `.trim();
24
25
  const indexMjsText = `
25
- export const schema = ${JSON.stringify(schema)}
26
+ export const schemas = ${JSON.stringify(schemasOnly)}
26
27
  `.trim();
27
- const indexDtsText = getIndexDts(schema, normalizedOptions);
28
+ const indexDtsText = getIndexDts(schemas, config);
28
29
  await fs.writeFile(path.join(radsDbPath, "./index.js"), indexJsText);
29
30
  await fs.writeFile(path.join(radsDbPath, "./index.mjs"), indexMjsText);
30
31
  await fs.writeFile(path.join(radsDbPath, "./index.d.ts"), indexDtsText);
@@ -38,67 +39,70 @@ export const schema = ${JSON.stringify(schema)}
38
39
  main: "./index.js",
39
40
  module: "./index.mjs",
40
41
  types: "./index.d.ts"
41
- // browser: 'index-browser.js',
42
42
  },
43
43
  null,
44
44
  2
45
45
  )
46
46
  );
47
- console.timeEnd("[rads-db] Schema generated in");
47
+ console.timeEnd('"node_modules/_rads-db" generated in');
48
48
  }
49
- export async function getSchema(normalizedOptions) {
50
- const { entitiesDir, apiUrl } = normalizedOptions;
51
- let schema;
52
- if (entitiesDir) {
53
- if (!fs2.existsSync(entitiesDir))
54
- await fs.mkdir(entitiesDir, { recursive: true });
55
- const response = await fs.readdir(entitiesDir, { withFileTypes: true });
56
- const entities = {};
57
- for (const file of response) {
58
- if (!file.isFile())
59
- continue;
60
- if (!file.name.endsWith(".ts"))
61
- continue;
62
- const text = await fs.readFile(path.resolve(entitiesDir, file.name), "utf-8");
63
- entities[file.name.slice(0, -3)] = text;
64
- }
65
- schema = parseSchema(entities);
66
- } else if (apiUrl) {
67
- const url = new URL("radsTunnel", apiUrl);
68
- const fetchResponse = await fetch(url.href, {
69
- method: "POST",
70
- headers: { "content-type": "application/json" },
71
- body: JSON.stringify({ method: "_schema" })
72
- });
73
- schema = await fetchResponse.json();
74
- if (!schema) {
75
- throw new Error("Could not download schema from the server. Please check the server URL.");
49
+ async function loadConfig() {
50
+ const jiti = createJiti(process.cwd());
51
+ const paths = ["./rads.config.ts", "./rads.config.js"];
52
+ let config;
53
+ for (const p of paths) {
54
+ config = await jiti.import(p, { try: true });
55
+ if (config)
56
+ break;
57
+ }
58
+ if (!config) {
59
+ throw new Error(
60
+ 'File "./rads.config.ts" was not found. Please make sure it is present in the root of your project.'
61
+ );
62
+ }
63
+ return config;
64
+ }
65
+ export async function getSchemas(config) {
66
+ const result = {};
67
+ for (const key in config.dataSources) {
68
+ if (!config.dataSources[key].schema) {
69
+ throw new Error(`Data source "${key}" does not have a schema. Please, specify it in rads.config.ts`);
76
70
  }
77
- } else {
78
- throw new Error("Please specify entitiesDir or apiUrl");
71
+ result[key] = await config.dataSources[key].schema();
79
72
  }
80
- return schema;
73
+ return result;
74
+ }
75
+ function getIndexDts(schemas, config) {
76
+ const parts = [];
77
+ const rootTypeFields = [];
78
+ for (const key in schemas) {
79
+ let rootTypeName = _.camelCase(key);
80
+ rootTypeName = rootTypeName[0].toUpperCase() + rootTypeName.slice(1);
81
+ const indexDtsStr = getIndexDtsInner(schemas[key].schema, rootTypeName, schemas[key].entitiesDir);
82
+ rootTypeFields.push(`${key}: ${rootTypeName}`);
83
+ parts.push(indexDtsStr);
84
+ }
85
+ parts.push(
86
+ `
87
+ export interface RadsDb {
88
+ ${rootTypeFields.join("\n")}
81
89
  }
82
- function normalizeOptions(options) {
83
- options = options || {};
84
- if (options.entitiesDir && options.apiUrl)
85
- throw new Error('You cannot specify both "apiUrl" and "entitiesDir". Choose one.');
86
- if (options.apiUrl)
87
- return options;
88
- return { entitiesDir: "./entities", ...options };
90
+ `.trim()
91
+ );
92
+ return parts.join("\n\n");
89
93
  }
90
- export function getIndexDts(schema, options) {
94
+ export function getIndexDtsInner(schema, rootTypeName, entitiesDir) {
91
95
  const imports = [];
92
96
  const rootFields = [];
93
97
  const whereTypes = [];
94
98
  const entityMeta = [];
95
- const schemaTypesStr = options.entitiesDir ? "" : getEntityTypesStrFromSchema(schema);
99
+ const schemaTypesStr = entitiesDir ? "" : getEntityTypesStrFromSchema(schema);
96
100
  for (const key in schema) {
97
101
  const type = schema[key];
98
102
  if (!type.fields)
99
103
  continue;
100
- if (options.entitiesDir && type.sourceFile) {
101
- imports.push(`import type { ${type.name} } from '../../${options.entitiesDir}/${type.sourceFile}'`);
104
+ if (entitiesDir && type.sourceFile) {
105
+ imports.push(`import type { ${type.name} } from '../../${entitiesDir}/${type.sourceFile}'`);
102
106
  }
103
107
  if (type.decorators?.entity) {
104
108
  rootFields.push(`${type.handle}: EntityMethods<${type.name}, '${type.name}'>`);
@@ -161,7 +165,7 @@ interface Reference_Where {
161
165
 
162
166
  ${whereTypes.join("\n\n")}
163
167
 
164
- export interface RadsDb {
168
+ export interface ${rootTypeName} {
165
169
  _schema: any
166
170
  uploadFile: (args: FileUploadArgs, ctx?: RadsRequestContext) => Promise<{ url: string }>
167
171
  ${rootFields.join("\n")}
@@ -10,7 +10,7 @@ function radsDbVite(options) {
10
10
  name: "rads-db",
11
11
  config(config, env) {},
12
12
  async configResolved(config) {
13
- await (0, _node.generateClient)(options);
13
+ await (0, _node.generateClient)();
14
14
  },
15
15
  configureServer(server) {
16
16
  server.middlewares.use((req, res, next) => {
@@ -6,7 +6,7 @@ export function radsDbVite(options) {
6
6
  config(config, env) {
7
7
  },
8
8
  async configResolved(config) {
9
- await generateClient(options);
9
+ await generateClient();
10
10
  },
11
11
  configureServer(server) {
12
12
  server.middlewares.use((req, res, next) => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "rads-db",
3
- "version": "3.0.84",
3
+ "version": "3.1.2",
4
4
  "packageManager": "pnpm@8.6.1",
5
5
  "description": "Say goodbye to boilerplate code and hello to efficient and elegant syntax.",
6
6
  "author": "",
@@ -12,6 +12,11 @@
12
12
  "require": "./dist/index.cjs",
13
13
  "import": "./dist/index.mjs"
14
14
  },
15
+ "./config": {
16
+ "types": "./dist/config.d.ts",
17
+ "require": "./dist/config.cjs",
18
+ "import": "./dist/config.mjs"
19
+ },
15
20
  "./drivers/*": {
16
21
  "types": "./drivers/*.d.ts",
17
22
  "require": "./drivers/*.cjs",
@@ -75,6 +80,7 @@
75
80
  "@fastify/deepmerge": "^1.3.0",
76
81
  "dataloader": "^2.2.2",
77
82
  "ignore": "^5.2.4",
83
+ "jiti": "^2.4.2",
78
84
  "klaw": "^4.1.0",
79
85
  "lodash": "^4.17.21",
80
86
  "uuid": ">=8",
@@ -104,7 +110,7 @@
104
110
  "scripts": {
105
111
  "test": "vitest --run && vitest typecheck --run",
106
112
  "link-rads-db": "symlink-dir ./test/_rads-db ./node_modules/_rads-db",
107
- "generate-test-schema": "ts-node ./src/integrations/cli -d './test/entities'",
113
+ "generate-test-schema": "jiti ./src/integrations/cli",
108
114
  "dev": "pnpm install && pnpm link-rads-db && pnpm build && pnpm generate-test-schema && vitest --ui --test-timeout 300000 --typecheck",
109
115
  "lint": "cross-env NODE_ENV=production eslint src/**/*.* test/**/*.*",
110
116
  "build": "unbuild"