nuxt-directus-sdk 0.0.3 → 0.0.4

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.
package/README.md CHANGED
@@ -5,14 +5,14 @@
5
5
  [![License][license-src]][license-href]
6
6
  [![Nuxt][nuxt-src]][nuxt-href]
7
7
 
8
- > A bunch of directus helpers for nuxt applications
8
+ > A Nuxt 3 Directus module that uses the official Directus 11 SDK
9
9
 
10
10
  - [✨  Release Notes](/CHANGELOG.md)
11
11
 
12
12
  ## Features
13
13
 
14
- - ⛰  Built-in Directus auth and type generation
15
- - 🚠  Built-in helpers and utils
14
+ - ⛰  Directus authentication out of the box
15
+ - 🚠  Automatic type generation based on Directus collections
16
16
 
17
17
  ## Quick Setup
18
18
 
package/dist/module.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
2
  import { Query } from '@directus/sdk';
3
- import { AllCollections } from '#build/types/directus';
3
+ import { AllDirectusCollections } from '#build/types/directus';
4
4
 
5
5
  interface ModuleOptions {
6
6
  /**
@@ -17,21 +17,21 @@ interface ModuleOptions {
17
17
  adminToken?: string;
18
18
  /**
19
19
  * Fetch the user serverside
20
- *
21
- * @default true
22
- */
20
+ *
21
+ * @default true
22
+ */
23
23
  fetchUser?: boolean;
24
24
  /**
25
- * Directus Auth Options
26
- * @default {}
27
- * @type Query<AllCollections, AllCollections['directus_users']>
28
- */
29
- fetchUserParams?: Query<AllCollections, AllCollections['directus_users']>;
25
+ * Directus Auth Options
26
+ * @default {}
27
+ * @type Query<AllDirectusCollections, AllDirectusCollections['directus_users']>
28
+ */
29
+ fetchUserParams?: Query<AllDirectusCollections, AllDirectusCollections['directus_users']>;
30
30
  /**
31
31
  * Add Directus Admin in Nuxt Devtools
32
32
  *
33
- * @default false
34
- */
33
+ * @default true
34
+ */
35
35
  devtools?: boolean;
36
36
  /**
37
37
  * Token Cookie Name
@@ -40,37 +40,43 @@ interface ModuleOptions {
40
40
  */
41
41
  cookieNameAccessToken?: string;
42
42
  /**
43
- * Refresh Token Cookie Name
44
- * @type string
45
- * @default 'directus_refresh_token'
46
- */
43
+ * Refresh Token Cookie Name
44
+ * @type string
45
+ * @default 'directus_refresh_token'
46
+ */
47
47
  cookieNameRefreshToken?: string;
48
48
  /**
49
- * The max age for auth cookies in seconds.
50
- * This should match your directus env key AUTH_TOKEN_TTL
51
- * @type string
52
- * @default 900
53
- */
49
+ * The max age for auth cookies in seconds.
50
+ * This should match your directus env key AUTH_TOKEN_TTL
51
+ * @type string
52
+ * @default 900
53
+ */
54
54
  cookieMaxAge?: number;
55
55
  /**
56
- * The max age for auth cookies in seconds.
57
- * This should match your directus env key REFRESH_TOKEN_TTL
58
- * @type string
59
- * @default 604800
60
- */
56
+ * The max age for auth cookies in seconds.
57
+ * This should match your directus env key REFRESH_TOKEN_TTL
58
+ * @type string
59
+ * @default 604800
60
+ */
61
61
  cookieMaxAgeRefreshToken?: number;
62
62
  /**
63
- * The SameSite attribute for auth cookies.
64
- * @type string
65
- * @default 'lax'
66
- */
63
+ * The SameSite attribute for auth cookies.
64
+ * @type string
65
+ * @default 'lax'
66
+ */
67
67
  cookieSameSite?: 'strict' | 'lax' | 'none' | undefined;
68
68
  /**
69
- * The Secure attribute for auth cookies.
70
- * @type boolean
71
- * @default false
72
- */
69
+ * The Secure attribute for auth cookies.
70
+ * @type boolean
71
+ * @default false
72
+ */
73
73
  cookieSecure?: boolean;
74
+ /**
75
+ * The Secure attribute for auth cookies.
76
+ * @type string
77
+ * @default ''
78
+ */
79
+ typePrefix?: string;
74
80
  }
75
81
  declare const _default: _nuxt_schema.NuxtModule<ModuleOptions>;
76
82
 
package/dist/module.d.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import * as _nuxt_schema from '@nuxt/schema';
2
2
  import { Query } from '@directus/sdk';
3
- import { AllCollections } from '#build/types/directus';
3
+ import { AllDirectusCollections } from '#build/types/directus';
4
4
 
5
5
  interface ModuleOptions {
6
6
  /**
@@ -17,21 +17,21 @@ interface ModuleOptions {
17
17
  adminToken?: string;
18
18
  /**
19
19
  * Fetch the user serverside
20
- *
21
- * @default true
22
- */
20
+ *
21
+ * @default true
22
+ */
23
23
  fetchUser?: boolean;
24
24
  /**
25
- * Directus Auth Options
26
- * @default {}
27
- * @type Query<AllCollections, AllCollections['directus_users']>
28
- */
29
- fetchUserParams?: Query<AllCollections, AllCollections['directus_users']>;
25
+ * Directus Auth Options
26
+ * @default {}
27
+ * @type Query<AllDirectusCollections, AllDirectusCollections['directus_users']>
28
+ */
29
+ fetchUserParams?: Query<AllDirectusCollections, AllDirectusCollections['directus_users']>;
30
30
  /**
31
31
  * Add Directus Admin in Nuxt Devtools
32
32
  *
33
- * @default false
34
- */
33
+ * @default true
34
+ */
35
35
  devtools?: boolean;
36
36
  /**
37
37
  * Token Cookie Name
@@ -40,37 +40,43 @@ interface ModuleOptions {
40
40
  */
41
41
  cookieNameAccessToken?: string;
42
42
  /**
43
- * Refresh Token Cookie Name
44
- * @type string
45
- * @default 'directus_refresh_token'
46
- */
43
+ * Refresh Token Cookie Name
44
+ * @type string
45
+ * @default 'directus_refresh_token'
46
+ */
47
47
  cookieNameRefreshToken?: string;
48
48
  /**
49
- * The max age for auth cookies in seconds.
50
- * This should match your directus env key AUTH_TOKEN_TTL
51
- * @type string
52
- * @default 900
53
- */
49
+ * The max age for auth cookies in seconds.
50
+ * This should match your directus env key AUTH_TOKEN_TTL
51
+ * @type string
52
+ * @default 900
53
+ */
54
54
  cookieMaxAge?: number;
55
55
  /**
56
- * The max age for auth cookies in seconds.
57
- * This should match your directus env key REFRESH_TOKEN_TTL
58
- * @type string
59
- * @default 604800
60
- */
56
+ * The max age for auth cookies in seconds.
57
+ * This should match your directus env key REFRESH_TOKEN_TTL
58
+ * @type string
59
+ * @default 604800
60
+ */
61
61
  cookieMaxAgeRefreshToken?: number;
62
62
  /**
63
- * The SameSite attribute for auth cookies.
64
- * @type string
65
- * @default 'lax'
66
- */
63
+ * The SameSite attribute for auth cookies.
64
+ * @type string
65
+ * @default 'lax'
66
+ */
67
67
  cookieSameSite?: 'strict' | 'lax' | 'none' | undefined;
68
68
  /**
69
- * The Secure attribute for auth cookies.
70
- * @type boolean
71
- * @default false
72
- */
69
+ * The Secure attribute for auth cookies.
70
+ * @type boolean
71
+ * @default false
72
+ */
73
73
  cookieSecure?: boolean;
74
+ /**
75
+ * The Secure attribute for auth cookies.
76
+ * @type string
77
+ * @default ''
78
+ */
79
+ typePrefix?: string;
74
80
  }
75
81
  declare const _default: _nuxt_schema.NuxtModule<ModuleOptions>;
76
82
 
package/dist/module.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nuxt-directus-sdk",
3
- "version": "0.0.3",
3
+ "version": "0.0.4",
4
4
  "configKey": "directus",
5
5
  "compatibility": {
6
6
  "nuxt": "^3.0.0",
package/dist/module.mjs CHANGED
@@ -1,13 +1,14 @@
1
1
  import { defu } from 'defu';
2
- import { useLogger, defineNuxtModule, createResolver, addPlugin, addImportsDir, addComponentsDir, addTypeTemplate } from '@nuxt/kit';
2
+ import { useLogger, defineNuxtModule, tryResolveModule, createResolver, addPlugin, addImportsDir, addComponentsDir, addTypeTemplate, addImportsSources } from '@nuxt/kit';
3
3
  import { joinURL } from 'ufo';
4
4
  import { createDirectus, authentication, rest, readCollections, readFields, readRelations } from '@directus/sdk';
5
+ import { pascalCase } from 'change-case';
5
6
 
6
7
  const name = "nuxt-directus-sdk";
7
- const version = "0.0.3";
8
+ const version = "0.0.4";
8
9
 
9
10
  function warn(message) {
10
- useLogger(message);
11
+ useLogger("nuxt-directus-sdk").warn(message);
11
12
  }
12
13
  async function generateTypes(options) {
13
14
  const collections = await getCollections(options);
@@ -15,7 +16,7 @@ async function generateTypes(options) {
15
16
  const types = [];
16
17
  Object.values(collections).forEach((collection) => {
17
18
  const collectionName = collection.collection;
18
- const typeName = pascalCase(collectionName);
19
+ const typeName = collectionName.startsWith("directus_") ? pascalCase(collectionName) : pascalCase(`${options.prefix}${collectionName}`);
19
20
  types.push(`${collectionName}: ${typeName}[]`);
20
21
  typeValues += `export type ${typeName} = {
21
22
  `;
@@ -32,25 +33,32 @@ async function generateTypes(options) {
32
33
  });
33
34
  typeValues += "};\n\n";
34
35
  });
35
- typeValues += `export interface AllCollections {
36
- ${types.map((x) => ` ${x};`).join("\n")}
37
- };
36
+ return `
37
+ // This file is auto-generated by @nuxtjs/directus-sdk
38
+ ${typeValues}
38
39
 
39
- interface UsersCollections {
40
- ${types.filter((item) => !item.startsWith("directus_")).map((x) => ` ${x};`).join("\n")}
41
- };
40
+ export interface AllDirectusCollections {
41
+ ${types.map((x) => ` ${x};`).join("\n")}
42
+ };
42
43
 
43
- declare global {
44
- interface DirectusCollections {
45
- ${types.filter((item) => !item.startsWith("directus_")).map((x) => ` ${x};`).join("\n")}
46
- };
47
- }
44
+ export interface DirectusSchema {
45
+ ${types.filter((item) => !item.startsWith("directus_")).map((x) => ` ${x};`).join("\n")}
46
+ };
47
+
48
+ declare global {
49
+ ${typeValues.replaceAll("export type", "type")}
50
+
51
+ interface AllDirectusCollections {
52
+ ${types.map((x) => ` ${x};`).join("\n")}
53
+ };
54
+
55
+ interface DirectusSchema {
56
+ ${types.filter((item) => !item.startsWith("directus_")).map((x) => ` ${x};`).join("\n")}
57
+ };
58
+ }
59
+
60
+ export {};
48
61
  `;
49
- typeValues += "\n";
50
- return typeValues;
51
- }
52
- function pascalCase(str) {
53
- return str.split(" ").flatMap((x) => x.split("_")).flatMap((y) => y.split("-")).map((x) => x.charAt(0).toUpperCase() + x.slice(1)).join("");
54
62
  }
55
63
  function getType(field) {
56
64
  let type = "";
@@ -81,11 +89,11 @@ function getType(field) {
81
89
  async function getCollections(options) {
82
90
  const directus = createDirectus(options.url).with(authentication("json", { autoRefresh: false })).with(rest());
83
91
  directus.setToken(options.token);
84
- const rawCollections = await directus.request(readCollections());
85
92
  const collections = {};
86
- rawCollections.sort((a, b) => a.collection.localeCompare(b.collection)).forEach(
87
- (collection) => collections[collection.collection] = { ...collection, fields: [] }
88
- );
93
+ const rawCollections = await directus.request(readCollections());
94
+ rawCollections.sort((a, b) => a.collection.localeCompare(b.collection)).forEach((collection) => {
95
+ collections[collection.collection] = { ...collection, fields: [] };
96
+ });
89
97
  const fields = await directus.request(readFields());
90
98
  fields.sort((a, b) => a.field.localeCompare(b.field)).forEach((field) => {
91
99
  if (!collections[field.collection]) {
@@ -106,12 +114,8 @@ async function getCollections(options) {
106
114
  warn("No one collection");
107
115
  return;
108
116
  }
109
- const oneField = collections[relation.meta.one_collection]?.fields.find(
110
- (field) => field.field === relation.meta.one_field
111
- );
112
- const manyField = collections[relation.meta.many_collection]?.fields.find(
113
- (field) => field.field === relation.meta.many_field
114
- );
117
+ const oneField = collections[relation.meta.one_collection]?.fields.find((field) => field.field === relation.meta.one_field);
118
+ const manyField = collections[relation.meta.many_collection]?.fields.find((field) => field.field === relation.meta.many_field);
115
119
  if (oneField) {
116
120
  oneField.relation = {
117
121
  type: "many",
@@ -141,9 +145,9 @@ const module = defineNuxtModule({
141
145
  }
142
146
  },
143
147
  defaults: {
144
- url: process.env.DIRECTUS_URL,
145
- adminToken: process.env.DIRECTUS_ADMIN_TOKEN,
146
- devtools: false,
148
+ url: process.env.DIRECTUS_URL ?? "",
149
+ adminToken: process.env.DIRECTUS_ADMIN_TOKEN ?? "",
150
+ devtools: true,
147
151
  fetchUser: true,
148
152
  fetchUserParams: {},
149
153
  cookieNameAccessToken: "directus_access_token",
@@ -152,22 +156,20 @@ const module = defineNuxtModule({
152
156
  cookieMaxAge: 900,
153
157
  cookieMaxAgeRefreshToken: 604800,
154
158
  cookieSameSite: "lax",
155
- cookieSecure: false
159
+ cookieSecure: false,
160
+ typePrefix: ""
156
161
  },
157
162
  async setup(options, nuxt) {
163
+ if (!tryResolveModule("@directus/sdk")) {
164
+ logger.error("nuxt-directus-sdk requries @directus/sdk^11.0.3, install it with `npm i @directus/sdk`, `yarn add @directus/sdk`, `pnpm add @directus/sdk` or `bun install @directus/sdk`");
165
+ return;
166
+ }
158
167
  nuxt.options.runtimeConfig[configKey] = { adminToken: options.adminToken ?? "" };
159
168
  nuxt.options.runtimeConfig.public = nuxt.options.runtimeConfig.public || {};
160
169
  nuxt.options.runtimeConfig.public[configKey] = defu(nuxt.options.runtimeConfig.public[configKey], {
161
- url: options.url,
162
- fetchUser: options.fetchUser,
163
- fetchUserParams: options.fetchUserParams,
164
- devtools: options.devtools,
165
- cookieNameAccessToken: options.cookieNameAccessToken,
166
- cookieNameRefreshToken: options.cookieNameRefreshToken,
167
- cookieMaxAge: options.cookieMaxAge,
168
- cookieMaxAgeRefreshToken: options.cookieMaxAgeRefreshToken,
169
- cookieSameSite: options.cookieSameSite,
170
- cookieSecure: options.cookieSecure
170
+ ...options,
171
+ // Don't add the admin token to the public key
172
+ adminToken: null
171
173
  });
172
174
  const resolver = createResolver(import.meta.url);
173
175
  addPlugin(resolver.resolve("./runtime/plugin"));
@@ -233,7 +235,8 @@ const module = defineNuxtModule({
233
235
  getContents() {
234
236
  return generateTypes({
235
237
  url: options.url,
236
- token: options.adminToken
238
+ token: options.adminToken,
239
+ prefix: options.typePrefix ?? ""
237
240
  });
238
241
  }
239
242
  }).dst;
@@ -247,6 +250,57 @@ const module = defineNuxtModule({
247
250
  logger.info("Add DIRECTUS_ADMIN_TOKEN to the .env file to generate directus types");
248
251
  }
249
252
  }
253
+ addImportsSources({
254
+ from: "@directus/sdk",
255
+ imports: [
256
+ "createComment",
257
+ "updateComment",
258
+ "deleteComment",
259
+ "createField",
260
+ "createItem",
261
+ "createItems",
262
+ "deleteField",
263
+ "deleteFile",
264
+ "deleteFiles",
265
+ "readActivities",
266
+ "readActivity",
267
+ "deleteItem",
268
+ "deleteItems",
269
+ "deleteUser",
270
+ "deleteUsers",
271
+ "importFile",
272
+ "readCollection",
273
+ "readCollections",
274
+ "createCollection",
275
+ "updateCollection",
276
+ "deleteCollection",
277
+ "readField",
278
+ "readFieldsByCollection",
279
+ "readFields",
280
+ "readFile",
281
+ "readFiles",
282
+ "readItem",
283
+ "readItems",
284
+ "readSingleton",
285
+ "readMe",
286
+ "createUser",
287
+ "createUsers",
288
+ "readUser",
289
+ "readUsers",
290
+ "updateField",
291
+ "updateFile",
292
+ "updateFiles",
293
+ "updateFolder",
294
+ "updateFolders",
295
+ "updateItem",
296
+ "updateItems",
297
+ "updateSingleton",
298
+ "updateMe",
299
+ "updateUser",
300
+ "updateUsers",
301
+ "withToken"
302
+ ]
303
+ });
250
304
  }
251
305
  });
252
306
 
@@ -1,4 +1,4 @@
1
1
  import type { AuthenticationClient, DirectusClient, RestClient, WebSocketClient } from '@directus/sdk';
2
- import type { UsersCollections } from '#build/types/directus';
2
+ import type { DirectusSchema } from '#build/types/directus';
3
3
  export declare function useDirectusUrl(): string;
4
- export declare function useDirectus(token?: string): DirectusClient<UsersCollections> & AuthenticationClient<UsersCollections> & RestClient<UsersCollections> & WebSocketClient<UsersCollections>;
4
+ export declare function useDirectus(token?: string): DirectusClient<DirectusSchema> & AuthenticationClient<DirectusSchema> & RestClient<DirectusSchema> & WebSocketClient<DirectusSchema>;
@@ -2,7 +2,10 @@ import { authentication, createDirectus, realtime, rest } from "@directus/sdk";
2
2
  import { useDirectusTokens } from "./tokens.mjs";
3
3
  import { useRuntimeConfig } from "#app";
4
4
  export function useDirectusUrl() {
5
- return useRuntimeConfig().public.directus.url;
5
+ const url = useRuntimeConfig().public.directus.url;
6
+ if (url[url.length - 1] !== "/")
7
+ return `${url}/`;
8
+ return url;
6
9
  }
7
10
  function createDirectusStorage() {
8
11
  const tokens = useDirectusTokens();
@@ -1,5 +1,5 @@
1
1
  import type { Query } from '@directus/sdk';
2
- import type { AllCollections, DirectusFiles } from '#build/types/directus';
2
+ import type { AllDirectusCollections, DirectusFiles } from '#build/types/directus';
3
3
  export type DirectusThumbnailFormat = 'jpg' | 'png' | 'webp' | 'tiff';
4
4
  export type DirectusThumbnailFit = 'cover' | 'contain' | 'inside' | 'outside';
5
5
  export interface DirectusThumbnailOptions {
@@ -9,15 +9,16 @@ export interface DirectusThumbnailOptions {
9
9
  fit?: DirectusThumbnailFit;
10
10
  format?: DirectusThumbnailFormat;
11
11
  withoutEnlargement?: boolean;
12
- token?: string;
12
+ token?: string | boolean;
13
13
  }
14
14
  interface FileUpload {
15
15
  file: File;
16
16
  data?: Record<keyof DirectusFiles, string>;
17
17
  }
18
- export declare function uploadDirectusFile(files: FileUpload[], query: Query<AllCollections, AllCollections['directus_files']>): Promise<DirectusFiles[]>;
18
+ export declare function uploadDirectusFile(file: FileUpload, query?: Query<AllDirectusCollections, AllDirectusCollections['directus_files']>): Promise<DirectusFiles | null>;
19
+ export declare function uploadDirectusFiles(files: FileUpload[], query?: Query<AllDirectusCollections, AllDirectusCollections['directus_files']>): Promise<DirectusFiles[]>;
19
20
  export declare function getDirectusAssetUrl(fileId: string, options?: {
20
- token?: string;
21
+ token?: string | boolean;
21
22
  }): string;
22
23
  export declare function getDirectusThumbnailUrl(fileId: string, options?: DirectusThumbnailOptions): string;
23
24
  export {};
@@ -1,6 +1,11 @@
1
1
  import { uploadFiles } from "@directus/sdk";
2
2
  import { useDirectus, useDirectusUrl } from "./directus.mjs";
3
- export async function uploadDirectusFile(files, query) {
3
+ import { useDirectusTokens } from "./tokens.mjs";
4
+ export async function uploadDirectusFile(file, query) {
5
+ const result = await uploadDirectusFiles([file], query);
6
+ return result[0] ?? null;
7
+ }
8
+ export async function uploadDirectusFiles(files, query) {
4
9
  const directus = useDirectus();
5
10
  const formData = new FormData();
6
11
  files.forEach(({ file, data }, i) => {
@@ -14,15 +19,17 @@ export async function uploadDirectusFile(files, query) {
14
19
  return await directus.request(uploadFiles(formData, query));
15
20
  }
16
21
  export function getDirectusAssetUrl(fileId, options) {
17
- const directusUrl = useDirectusUrl();
18
- const url = new URL(`${directusUrl}assets/${fileId}`);
19
- if (options?.token)
20
- url.searchParams.append("access_token", options.token);
22
+ const url = new URL(`${useDirectusUrl()}assets/${fileId}`);
23
+ if (options?.token) {
24
+ if (typeof options.token === "string")
25
+ url.searchParams.append("access_token", options.token);
26
+ else
27
+ url.searchParams.append("access_token", useDirectusTokens().accessToken.value ?? "");
28
+ }
21
29
  return url.href;
22
30
  }
23
31
  export function getDirectusThumbnailUrl(fileId, options) {
24
- const directusUrl = useDirectusUrl();
25
- const url = new URL(`${directusUrl}assets/${fileId}`);
32
+ const url = new URL(`${useDirectusUrl()}assets/${fileId}`);
26
33
  if (options) {
27
34
  if (options.width)
28
35
  url.searchParams.append("width", options.width.toFixed(0));
@@ -36,8 +43,12 @@ export function getDirectusThumbnailUrl(fileId, options) {
36
43
  url.searchParams.append("fit", options.fit);
37
44
  if (options.format)
38
45
  url.searchParams.append("format", options.format);
39
- if (options.token)
40
- url.searchParams.append("access_token", options.token);
46
+ if (options?.token) {
47
+ if (typeof options.token === "string")
48
+ url.searchParams.append("access_token", options.token);
49
+ else
50
+ url.searchParams.append("access_token", useDirectusTokens().accessToken.value ?? "");
51
+ }
41
52
  }
42
53
  return url.href;
43
54
  }
@@ -1,5 +1,5 @@
1
1
  export declare function useToast(): {
2
- log: (message: string) => Promise<void>;
2
+ log: (message: string, options?: import("vue-toastification/dist/types/types").ToastOptions | undefined) => Promise<void>;
3
3
  success: (message: string, options?: (import("vue-toastification/dist/types/types").ToastOptions & {
4
4
  type?: import("vue-toastification").TYPE.SUCCESS | undefined;
5
5
  }) | undefined) => Promise<void>;
@@ -1,9 +1,9 @@
1
1
  import { useToast as useToastFn } from "vue-toastification";
2
2
  export function useToast() {
3
3
  const toast = useToastFn();
4
- async function log(message) {
4
+ async function log(message, options) {
5
5
  if (process.client)
6
- toast(message);
6
+ toast(message, options);
7
7
  else
8
8
  console.log(message);
9
9
  }
@@ -2,7 +2,7 @@ import { useDomain } from "./domain.mjs";
2
2
  import { useCookie, useNuxtApp, useRuntimeConfig } from "#app";
3
3
  export function getCookieDomain() {
4
4
  const domain = useDomain();
5
- return !domain.value.includes("localhost") ? `.${domain.value}` : void 0;
5
+ return domain.value.includes("localhost") || domain.value.includes("127.0.0.1") || domain.value.includes("0.0.0.0") ? void 0 : `.${domain.value}`;
6
6
  }
7
7
  function directusCookie(name, cookieOptions) {
8
8
  const nuxtApp = useNuxtApp();
@@ -13,11 +13,13 @@ export default defineNuxtPlugin(async (nuxt) => {
13
13
  );
14
14
  if (mainDomain)
15
15
  domain.value = `${mainDomain}.${topLevelDomains.join(".")}`;
16
+ else if (host.includes("127.0.0.1") || host.includes("0.0.0.0"))
17
+ domain.value = host.split(":")?.[0] ?? "";
16
18
  else if (host.includes("localhost"))
17
- domain.value = host.split(".").at(-1) ?? "";
19
+ domain.value = host.split(".")?.at(-1) ?? "";
18
20
  else
19
21
  domain.value = host;
20
- subdomain.value = labels[0];
22
+ subdomain.value = labels?.[0] ?? "";
21
23
  }
22
24
  }
23
25
  const config = useRuntimeConfig();
@@ -1,7 +1,7 @@
1
1
  import type { AuthenticationClient, DirectusClient, RestClient } from '@directus/sdk';
2
2
  import type { H3Event } from 'h3';
3
- import type { UsersCollections } from '#build/types/directus';
3
+ import type { DirectusSchema } from '#build/types/directus';
4
4
  export declare function useDirectusAccessToken(event: H3Event): string | undefined;
5
5
  export declare function useDirectusUrl(): string;
6
- export declare function useDirectus(token?: string): DirectusClient<UsersCollections> & AuthenticationClient<UsersCollections> & RestClient<UsersCollections>;
7
- export declare function useAdminDirectus(): DirectusClient<UsersCollections> & AuthenticationClient<UsersCollections> & RestClient<UsersCollections>;
6
+ export declare function useDirectus(token?: string): DirectusClient<DirectusSchema> & AuthenticationClient<DirectusSchema> & RestClient<DirectusSchema>;
7
+ export declare function useAdminDirectus(): DirectusClient<DirectusSchema> & AuthenticationClient<DirectusSchema> & RestClient<DirectusSchema>;
@@ -2,6 +2,7 @@ import type { Collections } from './generate.types';
2
2
  export interface OASOptions {
3
3
  url: string;
4
4
  token: string;
5
+ prefix: string;
5
6
  }
6
7
  export declare function generateTypes(options: OASOptions): Promise<string>;
7
8
  export declare function getCollections(options: OASOptions): Promise<Collections>;
@@ -1,7 +1,8 @@
1
1
  import { useLogger } from "@nuxt/kit";
2
2
  import { authentication, createDirectus, readCollections, readFields, readRelations, rest } from "@directus/sdk";
3
+ import { pascalCase } from "change-case";
3
4
  function warn(message) {
4
- useLogger(message);
5
+ useLogger("nuxt-directus-sdk").warn(message);
5
6
  }
6
7
  export async function generateTypes(options) {
7
8
  const collections = await getCollections(options);
@@ -9,7 +10,7 @@ export async function generateTypes(options) {
9
10
  const types = [];
10
11
  Object.values(collections).forEach((collection) => {
11
12
  const collectionName = collection.collection;
12
- const typeName = pascalCase(collectionName);
13
+ const typeName = collectionName.startsWith("directus_") ? pascalCase(collectionName) : pascalCase(`${options.prefix}${collectionName}`);
13
14
  types.push(`${collectionName}: ${typeName}[]`);
14
15
  typeValues += `export type ${typeName} = {
15
16
  `;
@@ -26,25 +27,32 @@ export async function generateTypes(options) {
26
27
  });
27
28
  typeValues += "};\n\n";
28
29
  });
29
- typeValues += `export interface AllCollections {
30
- ${types.map((x) => ` ${x};`).join("\n")}
31
- };
30
+ return `
31
+ // This file is auto-generated by @nuxtjs/directus-sdk
32
+ ${typeValues}
32
33
 
33
- interface UsersCollections {
34
- ${types.filter((item) => !item.startsWith("directus_")).map((x) => ` ${x};`).join("\n")}
35
- };
34
+ export interface AllDirectusCollections {
35
+ ${types.map((x) => ` ${x};`).join("\n")}
36
+ };
36
37
 
37
- declare global {
38
- interface DirectusCollections {
39
- ${types.filter((item) => !item.startsWith("directus_")).map((x) => ` ${x};`).join("\n")}
40
- };
41
- }
38
+ export interface DirectusSchema {
39
+ ${types.filter((item) => !item.startsWith("directus_")).map((x) => ` ${x};`).join("\n")}
40
+ };
41
+
42
+ declare global {
43
+ ${typeValues.replaceAll("export type", "type")}
44
+
45
+ interface AllDirectusCollections {
46
+ ${types.map((x) => ` ${x};`).join("\n")}
47
+ };
48
+
49
+ interface DirectusSchema {
50
+ ${types.filter((item) => !item.startsWith("directus_")).map((x) => ` ${x};`).join("\n")}
51
+ };
52
+ }
53
+
54
+ export {};
42
55
  `;
43
- typeValues += "\n";
44
- return typeValues;
45
- }
46
- function pascalCase(str) {
47
- return str.split(" ").flatMap((x) => x.split("_")).flatMap((y) => y.split("-")).map((x) => x.charAt(0).toUpperCase() + x.slice(1)).join("");
48
56
  }
49
57
  function getType(field) {
50
58
  let type = "";
@@ -75,11 +83,11 @@ function getType(field) {
75
83
  export async function getCollections(options) {
76
84
  const directus = createDirectus(options.url).with(authentication("json", { autoRefresh: false })).with(rest());
77
85
  directus.setToken(options.token);
78
- const rawCollections = await directus.request(readCollections());
79
86
  const collections = {};
80
- rawCollections.sort((a, b) => a.collection.localeCompare(b.collection)).forEach(
81
- (collection) => collections[collection.collection] = { ...collection, fields: [] }
82
- );
87
+ const rawCollections = await directus.request(readCollections());
88
+ rawCollections.sort((a, b) => a.collection.localeCompare(b.collection)).forEach((collection) => {
89
+ collections[collection.collection] = { ...collection, fields: [] };
90
+ });
83
91
  const fields = await directus.request(readFields());
84
92
  fields.sort((a, b) => a.field.localeCompare(b.field)).forEach((field) => {
85
93
  if (!collections[field.collection]) {
@@ -100,12 +108,8 @@ export async function getCollections(options) {
100
108
  warn("No one collection");
101
109
  return;
102
110
  }
103
- const oneField = collections[relation.meta.one_collection]?.fields.find(
104
- (field) => field.field === relation.meta.one_field
105
- );
106
- const manyField = collections[relation.meta.many_collection]?.fields.find(
107
- (field) => field.field === relation.meta.many_field
108
- );
111
+ const oneField = collections[relation.meta.one_collection]?.fields.find((field) => field.field === relation.meta.one_field);
112
+ const manyField = collections[relation.meta.many_collection]?.fields.find((field) => field.field === relation.meta.many_field);
109
113
  if (oneField) {
110
114
  oneField.relation = {
111
115
  type: "many",
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-directus-sdk",
3
3
  "type": "module",
4
- "version": "0.0.3",
4
+ "version": "0.0.4",
5
5
  "description": "A nuxt module that uses the directus SDK",
6
6
  "author": "Matthew Rollinson <matt@rolley.io>",
7
7
  "license": "MIT",