nuxt-directus-sdk 2.1.4 → 3.0.0

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/dist/module.d.mts CHANGED
@@ -14,18 +14,6 @@ interface ModuleOptions {
14
14
  * @type string
15
15
  */
16
16
  adminToken?: string;
17
- /**
18
- * Fetch the user serverside
19
- *
20
- * @default true
21
- */
22
- fetchUser?: boolean;
23
- /**
24
- * Directus Auth Options
25
- * @default {}
26
- * @type Query<DirectusSchema, DirectusSchema['directus_users']>['fields']
27
- */
28
- fetchUserFields?: Query<DirectusSchema, DirectusSchema['directus_users']>['fields'];
29
17
  /**
30
18
  * Add Directus Admin in Nuxt Devtools
31
19
  *
@@ -33,61 +21,104 @@ interface ModuleOptions {
33
21
  */
34
22
  devtools?: boolean;
35
23
  /**
36
- * Token Cookie Name
37
- * @type string
38
- * @default 'directus_access_token'
39
- */
40
- cookieNameAccessToken?: string;
41
- /**
42
- * Refresh Token Cookie Name
43
- * @type string
44
- * @default 'directus_refresh_token'
45
- */
46
- cookieNameRefreshToken?: string;
47
- /**
48
- * The max age for auth cookies in seconds.
49
- * This should match your directus env key AUTH_TOKEN_TTL
50
- * @type string
51
- * @default 900
52
- */
53
- cookieMaxAge?: number;
54
- /**
55
- * The max age for auth cookies in seconds.
56
- * This should match your directus env key REFRESH_TOKEN_TTL
57
- * @type string
58
- * @default 604800
59
- */
60
- cookieMaxAgeRefreshToken?: number;
61
- /**
62
- * The SameSite attribute for auth cookies.
63
- * @type string
64
- * @default 'lax'
65
- */
66
- cookieSameSite?: 'strict' | 'lax' | 'none' | undefined;
67
- /**
68
- * The Secure attribute for auth cookies.
69
- * @type boolean
70
- * @default false
71
- */
72
- cookieSecure?: boolean;
73
- /**
74
- * The Domain attribute for auth cookies.
75
- * @type string
76
- * @default undefined
77
- */
78
- cookieDomain?: boolean;
79
- /**
80
- * The prefix to your custom types
81
- * @type string
82
- * @default ''
83
- */
84
- typePrefix?: string;
85
- /**
86
- * A path to redirect a user to when not logged in using auth middleware
87
- * @type string
88
- * @default '/login'
24
+ * Auth options
89
25
  */
90
- loginPath?: string;
26
+ auth?: {
27
+ /**
28
+ * Enable auth middleware
29
+ * @default true
30
+ * @type boolean
31
+ *
32
+ */
33
+ enabled?: boolean;
34
+ /**
35
+ * Enable global auth middleware
36
+ * @default false
37
+ * @type boolean
38
+ */
39
+ enableGlobalAuthMiddleware?: boolean;
40
+ /**
41
+ * ReadMe fields to fetch
42
+ * @default []
43
+ * @type Query<AllDirectusCollections, AllDirectusCollections['directus_users']>['fields']
44
+ */
45
+ readMeFields?: Query<AllDirectusCollections, AllDirectusCollections['directus_users']>['fields'];
46
+ cookies?: {
47
+ /**
48
+ * Session token cookie name
49
+ * @default 'directus_access_token'
50
+ */
51
+ accessToken?: string;
52
+ /**
53
+ * Refresh token cookie name
54
+ * @default 'directus_refresh_token'
55
+ */
56
+ refreshToken?: string;
57
+ /**
58
+ * Logged in token cookie name
59
+ * @default 'directus_logged_in'
60
+ */
61
+ loggedInToken?: string;
62
+ /**
63
+ * Session token cookie max age
64
+ * @default 900
65
+ */
66
+ maxAge?: number;
67
+ /**
68
+ * Refresh token cookie max age
69
+ * @default 604800
70
+ */
71
+ maxAgeRefreshToken?: number;
72
+ /**
73
+ * SameSite cookie attribute
74
+ * @default 'lax'
75
+ */
76
+ sameSite?: 'lax' | 'strict' | 'none';
77
+ /**
78
+ * Secure cookie attribute
79
+ * @default false
80
+ * @type boolean
81
+ */
82
+ secure?: boolean;
83
+ /**
84
+ * Domain cookie attribute
85
+ * @default undefined
86
+ * @type string | undefined
87
+ */
88
+ domain?: string | undefined;
89
+ };
90
+ redirect?: {
91
+ /**
92
+ * Redirect to home page after login
93
+ * @default '/home'
94
+ */
95
+ home?: string;
96
+ /**
97
+ * Redirect to login page after logout
98
+ * @default '/auth/login'
99
+ */
100
+ login?: string;
101
+ /**
102
+ * Redirect to login page after logout
103
+ * @default '/auth/login'
104
+ */
105
+ logout?: string;
106
+ };
107
+ };
108
+ types?: {
109
+ /**
110
+ * Generate types for your Directus instance
111
+ * @type boolean
112
+ * @default true
113
+ */
114
+ enabled?: boolean;
115
+ /**
116
+ * The prefix to your custom types
117
+ * @type string
118
+ * @default ''
119
+ */
120
+ prefix?: string;
121
+ };
91
122
  }
92
123
  declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
93
124
 
@@ -95,7 +126,7 @@ declare module '@nuxt/schema' {
95
126
  interface ConfigSchema {
96
127
  directus?: ModuleOptions;
97
128
  publicRuntimeConfig?: {
98
- directus?: ModuleOptions;
129
+ directus?: Omit<ModuleOptions, 'adminToken'>;
99
130
  };
100
131
  }
101
132
  }
package/dist/module.d.ts CHANGED
@@ -14,18 +14,6 @@ interface ModuleOptions {
14
14
  * @type string
15
15
  */
16
16
  adminToken?: string;
17
- /**
18
- * Fetch the user serverside
19
- *
20
- * @default true
21
- */
22
- fetchUser?: boolean;
23
- /**
24
- * Directus Auth Options
25
- * @default {}
26
- * @type Query<DirectusSchema, DirectusSchema['directus_users']>['fields']
27
- */
28
- fetchUserFields?: Query<DirectusSchema, DirectusSchema['directus_users']>['fields'];
29
17
  /**
30
18
  * Add Directus Admin in Nuxt Devtools
31
19
  *
@@ -33,61 +21,104 @@ interface ModuleOptions {
33
21
  */
34
22
  devtools?: boolean;
35
23
  /**
36
- * Token Cookie Name
37
- * @type string
38
- * @default 'directus_access_token'
39
- */
40
- cookieNameAccessToken?: string;
41
- /**
42
- * Refresh Token Cookie Name
43
- * @type string
44
- * @default 'directus_refresh_token'
45
- */
46
- cookieNameRefreshToken?: string;
47
- /**
48
- * The max age for auth cookies in seconds.
49
- * This should match your directus env key AUTH_TOKEN_TTL
50
- * @type string
51
- * @default 900
52
- */
53
- cookieMaxAge?: number;
54
- /**
55
- * The max age for auth cookies in seconds.
56
- * This should match your directus env key REFRESH_TOKEN_TTL
57
- * @type string
58
- * @default 604800
59
- */
60
- cookieMaxAgeRefreshToken?: number;
61
- /**
62
- * The SameSite attribute for auth cookies.
63
- * @type string
64
- * @default 'lax'
65
- */
66
- cookieSameSite?: 'strict' | 'lax' | 'none' | undefined;
67
- /**
68
- * The Secure attribute for auth cookies.
69
- * @type boolean
70
- * @default false
71
- */
72
- cookieSecure?: boolean;
73
- /**
74
- * The Domain attribute for auth cookies.
75
- * @type string
76
- * @default undefined
77
- */
78
- cookieDomain?: boolean;
79
- /**
80
- * The prefix to your custom types
81
- * @type string
82
- * @default ''
83
- */
84
- typePrefix?: string;
85
- /**
86
- * A path to redirect a user to when not logged in using auth middleware
87
- * @type string
88
- * @default '/login'
24
+ * Auth options
89
25
  */
90
- loginPath?: string;
26
+ auth?: {
27
+ /**
28
+ * Enable auth middleware
29
+ * @default true
30
+ * @type boolean
31
+ *
32
+ */
33
+ enabled?: boolean;
34
+ /**
35
+ * Enable global auth middleware
36
+ * @default false
37
+ * @type boolean
38
+ */
39
+ enableGlobalAuthMiddleware?: boolean;
40
+ /**
41
+ * ReadMe fields to fetch
42
+ * @default []
43
+ * @type Query<AllDirectusCollections, AllDirectusCollections['directus_users']>['fields']
44
+ */
45
+ readMeFields?: Query<AllDirectusCollections, AllDirectusCollections['directus_users']>['fields'];
46
+ cookies?: {
47
+ /**
48
+ * Session token cookie name
49
+ * @default 'directus_access_token'
50
+ */
51
+ accessToken?: string;
52
+ /**
53
+ * Refresh token cookie name
54
+ * @default 'directus_refresh_token'
55
+ */
56
+ refreshToken?: string;
57
+ /**
58
+ * Logged in token cookie name
59
+ * @default 'directus_logged_in'
60
+ */
61
+ loggedInToken?: string;
62
+ /**
63
+ * Session token cookie max age
64
+ * @default 900
65
+ */
66
+ maxAge?: number;
67
+ /**
68
+ * Refresh token cookie max age
69
+ * @default 604800
70
+ */
71
+ maxAgeRefreshToken?: number;
72
+ /**
73
+ * SameSite cookie attribute
74
+ * @default 'lax'
75
+ */
76
+ sameSite?: 'lax' | 'strict' | 'none';
77
+ /**
78
+ * Secure cookie attribute
79
+ * @default false
80
+ * @type boolean
81
+ */
82
+ secure?: boolean;
83
+ /**
84
+ * Domain cookie attribute
85
+ * @default undefined
86
+ * @type string | undefined
87
+ */
88
+ domain?: string | undefined;
89
+ };
90
+ redirect?: {
91
+ /**
92
+ * Redirect to home page after login
93
+ * @default '/home'
94
+ */
95
+ home?: string;
96
+ /**
97
+ * Redirect to login page after logout
98
+ * @default '/auth/login'
99
+ */
100
+ login?: string;
101
+ /**
102
+ * Redirect to login page after logout
103
+ * @default '/auth/login'
104
+ */
105
+ logout?: string;
106
+ };
107
+ };
108
+ types?: {
109
+ /**
110
+ * Generate types for your Directus instance
111
+ * @type boolean
112
+ * @default true
113
+ */
114
+ enabled?: boolean;
115
+ /**
116
+ * The prefix to your custom types
117
+ * @type string
118
+ * @default ''
119
+ */
120
+ prefix?: string;
121
+ };
91
122
  }
92
123
  declare const _default: _nuxt_schema.NuxtModule<ModuleOptions, ModuleOptions, false>;
93
124
 
@@ -95,7 +126,7 @@ declare module '@nuxt/schema' {
95
126
  interface ConfigSchema {
96
127
  directus?: ModuleOptions;
97
128
  publicRuntimeConfig?: {
98
- directus?: ModuleOptions;
129
+ directus?: Omit<ModuleOptions, 'adminToken'>;
99
130
  };
100
131
  }
101
132
  }
package/dist/module.mjs CHANGED
@@ -1,10 +1,10 @@
1
- import { useLogger, defineNuxtModule, createResolver, installModule, addPlugin, addImportsDir, addComponentsDir, addImportsSources, addTypeTemplate } from '@nuxt/kit';
1
+ import { useLogger, defineNuxtModule, createResolver, installModule, addPlugin, addRouteMiddleware, addImportsDir, addComponentsDir, addImportsSources, addTypeTemplate } from '@nuxt/kit';
2
2
  import { defu } from 'defu';
3
3
  import { generateTypes } from '../dist/runtime/types/index.js';
4
4
  import { useUrl } from '../dist/runtime/utils/index.js';
5
5
 
6
6
  const name = "nuxt-directus-sdk";
7
- const version = "2.1.4";
7
+ const version = "3.0.0";
8
8
 
9
9
  const configKey = "directus";
10
10
  const logger = useLogger("nuxt-directus-sdk");
@@ -22,31 +22,41 @@ const module = defineNuxtModule({
22
22
  url: import.meta.env.DIRECTUS_URL ?? "",
23
23
  adminToken: import.meta.env.DIRECTUS_ADMIN_TOKEN ?? "",
24
24
  devtools: true,
25
- fetchUser: true,
26
- fetchUserFields: [],
27
- cookieNameAccessToken: "directus_access_token",
28
- cookieNameRefreshToken: "directus_refresh_token",
29
- // Nuxt Cookies Docs @ https://nuxt.com/docs/api/composables/use-cookie
30
- cookieMaxAge: 900,
31
- cookieMaxAgeRefreshToken: 604800,
32
- cookieSameSite: "lax",
33
- cookieSecure: false,
34
- cookieDomain: void 0,
35
- typePrefix: "",
36
- loginPath: "/login"
25
+ types: {
26
+ enabled: true,
27
+ prefix: ""
28
+ },
29
+ auth: {
30
+ enabled: true,
31
+ enableGlobalAuthMiddleware: false,
32
+ readMeFields: [],
33
+ cookies: {
34
+ accessToken: "directus_access_token",
35
+ refreshToken: "directus_refresh_token",
36
+ loggedInToken: "directus_logged_in",
37
+ maxAge: 900,
38
+ maxAgeRefreshToken: 604800,
39
+ // Nuxt Cookies Docs @ https://nuxt.com/docs/api/composables/use-cookie
40
+ sameSite: "lax",
41
+ secure: false,
42
+ domain: void 0
43
+ },
44
+ redirect: {
45
+ home: "/",
46
+ login: "/account/login",
47
+ logout: "/"
48
+ }
49
+ }
37
50
  },
38
51
  async setup(options, nuxtApp) {
39
52
  if (!options.url) {
40
53
  logger.error("nuxt-directus-sdk requires a url to your Directus instance, set it in the config options or .env file as DIRECTUS_URL");
41
54
  return;
42
55
  }
43
- nuxtApp.options.runtimeConfig[configKey] = { adminToken: options.adminToken ?? "" };
56
+ nuxtApp.options.runtimeConfig[configKey] = options;
44
57
  nuxtApp.options.runtimeConfig.public = nuxtApp.options.runtimeConfig.public || {};
45
- nuxtApp.options.runtimeConfig.public[configKey] = defu(nuxtApp.options.runtimeConfig.public[configKey], {
46
- ...options,
47
- // Don't add the admin token to the public config
48
- adminToken: null
49
- });
58
+ nuxtApp.options.runtimeConfig.public[configKey] = defu(nuxtApp.options.runtimeConfig.public[configKey], options);
59
+ delete nuxtApp.options.runtimeConfig.public[configKey].adminToken;
50
60
  const resolver = createResolver(import.meta.url);
51
61
  await installModule("@nuxt/image", {
52
62
  directus: {
@@ -54,6 +64,11 @@ const module = defineNuxtModule({
54
64
  }
55
65
  });
56
66
  addPlugin(resolver.resolve("./runtime/plugin"));
67
+ addRouteMiddleware({
68
+ name: "auth",
69
+ path: resolver.resolve("./runtime/middleware/auth"),
70
+ global: options.auth?.enableGlobalAuthMiddleware
71
+ });
57
72
  addImportsDir(resolver.resolve("./runtime/composables"));
58
73
  addComponentsDir({
59
74
  path: resolver.resolve("./runtime/components"),
@@ -103,6 +118,7 @@ const module = defineNuxtModule({
103
118
  "readProviders",
104
119
  "readFolder",
105
120
  "readFolders",
121
+ "uploadFiles",
106
122
  "updateField",
107
123
  "updateFile",
108
124
  "updateFiles",
@@ -151,27 +167,29 @@ const module = defineNuxtModule({
151
167
  } else {
152
168
  logger.info("Set devtools to true to view the Directus admin panel from inside Nuxt Devtools");
153
169
  }
154
- if (options.adminToken) {
155
- logger.info("Generating Directus types");
156
- try {
157
- const typesPath = addTypeTemplate({
158
- filename: `types/${configKey}.d.ts`,
159
- getContents() {
160
- return generateTypes({
161
- url: useUrl(options.url),
162
- token: options.adminToken,
163
- prefix: options.typePrefix ?? ""
164
- });
165
- }
166
- }, { nitro: true, nuxt: true }).dst;
167
- nuxtApp.hook("prepare:types", (options2) => {
168
- options2.references.push({ path: typesPath });
169
- });
170
- } catch (error) {
171
- logger.error(error.message);
170
+ if (options.types?.enabled) {
171
+ if (!options.adminToken) {
172
+ logger.warn("Directus types generation is disabled, set the admin token in the config or .env file as DIRECTUS_ADMIN_TOKEN");
173
+ } else {
174
+ logger.info("Generating Directus types");
175
+ try {
176
+ const typesPath = addTypeTemplate({
177
+ filename: `types/${configKey}.d.ts`,
178
+ getContents() {
179
+ return generateTypes({
180
+ url: useUrl(options.url),
181
+ token: options.adminToken,
182
+ prefix: options.types?.prefix ?? ""
183
+ });
184
+ }
185
+ }, { nitro: true, nuxt: true }).dst;
186
+ nuxtApp.hook("prepare:types", (options2) => {
187
+ options2.references.push({ path: typesPath });
188
+ });
189
+ } catch (error) {
190
+ logger.error(error.message);
191
+ }
172
192
  }
173
- } else {
174
- logger.info("Add DIRECTUS_ADMIN_TOKEN to the .env file to generate directus types");
175
193
  }
176
194
  }
177
195
  });
@@ -16,12 +16,17 @@ export function useDirectusAuth() {
16
16
  const loggedIn = computed(() => user.value !== null);
17
17
  async function readMe() {
18
18
  try {
19
+ if (tokens.directusUrl.value !== config.public.directus.url) {
20
+ tokens.directusUrl.value = config.public.directus.url;
21
+ await logout();
22
+ throw new Error("Directus URL changed");
23
+ }
19
24
  if (!tokens.accessToken.value) {
20
25
  if (!tokens.refreshToken.value)
21
26
  throw new Error("No refresh token");
22
27
  await directus.refresh();
23
28
  }
24
- user.value = await directus.request(directusReadMe({ fields: config.public.directus.fetchUserFields }));
29
+ user.value = await directus.request(directusReadMe({ fields: config.public.directus.auth?.readMeFields ?? ["*"] }));
25
30
  } catch {
26
31
  user.value = null;
27
32
  }
@@ -32,21 +37,24 @@ export function useDirectusAuth() {
32
37
  const currentUser = user.value;
33
38
  if (!currentUser?.id)
34
39
  throw new Error("No user available");
35
- user.value = await directus.request(directusUpdateMe(data, { fields: config.public.directus.fetchUserFields }));
40
+ user.value = await directus.request(directusUpdateMe(data, { fields: config.public.directus.auth?.readMeFields ?? ["*"] }));
36
41
  return user.value;
37
42
  }
38
43
  async function login(email, password, options) {
39
- const response = await directus.login(email, password, options);
44
+ const response = await directus.login(email, password, { ...options, mode: "json" });
40
45
  if (!response.access_token)
41
46
  throw new Error("Login failed, please check your credentials.");
42
47
  await readMe();
43
48
  const redirect = options?.redirect ?? true;
44
49
  if (redirect !== false) {
45
50
  const route = router.currentRoute.value;
46
- if (typeof redirect !== "boolean")
51
+ if (typeof redirect !== "boolean") {
47
52
  navigateTo(redirect);
48
- else if (route?.query?.redirect)
53
+ } else if (route?.query?.redirect) {
49
54
  navigateTo({ path: decodeURIComponent(route.query.redirect) });
55
+ } else {
56
+ navigateTo(config.public.directus.auth?.redirect?.home ?? "/");
57
+ }
50
58
  }
51
59
  return {
52
60
  user: user.value,
@@ -82,6 +90,7 @@ export function useDirectusAuth() {
82
90
  async function logout() {
83
91
  try {
84
92
  await directus.logout();
93
+ await navigateTo(config.public.directus.auth?.redirect?.logout ?? config.public.directus.auth?.redirect?.home ?? "/");
85
94
  } finally {
86
95
  user.value = null;
87
96
  tokens.refreshToken.value = null;
@@ -27,7 +27,7 @@ function createDirectusStorage() {
27
27
  export function useDirectus(token) {
28
28
  const directus = createDirectus(useDirectusUrl()).with(authentication("json", {
29
29
  storage: createDirectusStorage(),
30
- autoRefresh: token !== ""
30
+ autoRefresh: token === ""
31
31
  })).with(rest()).with(realtime());
32
32
  if (token)
33
33
  directus.setToken(token);
@@ -7,7 +7,9 @@ export declare function uploadDirectusFile(file: DirectusFileUpload, query?: Que
7
7
  export declare function uploadDirectusFiles(files: DirectusFileUpload[], query?: Query<AllDirectusCollections, AllDirectusCollections['directus_files']>): Promise<any>;
8
8
  export type DirectusThumbnailFormat = 'jpg' | 'png' | 'webp' | 'tiff' | 'avif';
9
9
  export type DirectusThumbnailFit = 'cover' | 'contain' | 'inside' | 'outside';
10
- export interface DirectusThumbnailOptions {
10
+ export interface DirectusFileOptions {
11
+ filename?: string;
12
+ download?: boolean;
11
13
  width?: number;
12
14
  height?: number;
13
15
  quality?: number;
@@ -17,5 +19,5 @@ export interface DirectusThumbnailOptions {
17
19
  key?: string;
18
20
  token?: string | boolean;
19
21
  }
20
- export declare function getDirectusFileUrl(file: string | DirectusFiles, options?: DirectusThumbnailOptions): string;
22
+ export declare function getDirectusFileUrl(file: string | DirectusFiles, options?: DirectusFileOptions): string;
21
23
  export {};
@@ -16,11 +16,14 @@ export async function uploadDirectusFiles(files, query) {
16
16
  }
17
17
  formData.set("file", file);
18
18
  });
19
- return await directus.request(uploadFiles(formData, query));
19
+ return directus.request(uploadFiles(formData, query));
20
20
  }
21
21
  export function getDirectusFileUrl(file, options) {
22
22
  const fileId = typeof file === "string" ? file : file.id;
23
- const url = new URL(useDirectusUrl(`assets/${fileId}`));
23
+ const url = new URL(useDirectusUrl(`assets/${fileId}${options?.filename ? `/${options.filename}` : ""}`));
24
+ if (options?.download) {
25
+ url.searchParams.append("download", "true");
26
+ }
24
27
  if (options?.width) {
25
28
  url.searchParams.append("width", options.width.toFixed(0));
26
29
  }
@@ -1 +1 @@
1
- export declare function isVisualEditorPage(route: any): any;
1
+ export declare function isVisualEditorPage(route: any): boolean;
@@ -1,3 +1,3 @@
1
1
  export function isVisualEditorPage(route) {
2
- return route.query["visual-editor"] && route.query["visual-editor"] === "true";
2
+ return route.query["visual-editor"] === "true" || route.query["visual-editor"] === true || route.query["visual-editor"] === 1;
3
3
  }
@@ -1,5 +1,6 @@
1
1
  import type { CookieRef } from '#app';
2
2
  export interface DirectusTokens {
3
+ directusUrl: CookieRef<string | null>;
3
4
  accessToken: CookieRef<string | null>;
4
5
  refreshToken: CookieRef<string | null>;
5
6
  expires: CookieRef<number | null>;
@@ -9,37 +9,44 @@ function directusCookie(name, cookieOptions) {
9
9
  return cookie;
10
10
  }
11
11
  export function useDirectusTokens() {
12
- const config = useRuntimeConfig().public.directus;
12
+ const { cookies } = useRuntimeConfig().public.directus.auth;
13
13
  const sharedOptions = {
14
- sameSite: config.cookieSameSite,
15
- secure: config.cookieSecure,
16
- domain: config.cookieDomain
14
+ sameSite: cookies.sameSite,
15
+ secure: cookies.secure,
16
+ domain: cookies.domain
17
17
  };
18
+ function directusUrl() {
19
+ return directusCookie("directus_url", {
20
+ ...sharedOptions,
21
+ maxAge: cookies.maxAge
22
+ });
23
+ }
18
24
  function accessToken() {
19
- return directusCookie(config.cookieNameAccessToken, {
25
+ return directusCookie(cookies.accessToken, {
20
26
  ...sharedOptions,
21
- maxAge: config.cookieMaxAge
27
+ maxAge: cookies.maxAge
22
28
  });
23
29
  }
24
30
  function refreshToken() {
25
- return directusCookie(config.cookieNameRefreshToken, {
31
+ return directusCookie(cookies.refreshToken, {
26
32
  ...sharedOptions,
27
- maxAge: config.cookieMaxAgeRefreshToken
33
+ maxAge: cookies.maxAgeRefreshToken
28
34
  });
29
35
  }
30
36
  function expires() {
31
37
  return directusCookie("directus_access_expires", {
32
38
  ...sharedOptions,
33
- maxAge: config.cookieMaxAge
39
+ maxAge: cookies.maxAge
34
40
  });
35
41
  }
36
42
  function expiresAt() {
37
43
  return directusCookie("directus_access_expires_at", {
38
44
  ...sharedOptions,
39
- maxAge: config.cookieMaxAge
45
+ maxAge: cookies.maxAge
40
46
  });
41
47
  }
42
48
  return {
49
+ directusUrl: directusUrl(),
43
50
  accessToken: accessToken(),
44
51
  refreshToken: refreshToken(),
45
52
  expires: expires(),
@@ -7,10 +7,16 @@ import {
7
7
  export default defineNuxtRouteMiddleware((to) => {
8
8
  const config = useRuntimeConfig();
9
9
  const user = useDirectusUser();
10
+ const redirect = config.public.directus.auth?.redirect ?? {};
11
+ const loginPath = redirect.login ?? "/login";
12
+ const homePath = redirect.home ?? "/";
13
+ if (to.path === loginPath) {
14
+ return;
15
+ }
10
16
  if (!user.value) {
11
17
  return navigateTo({
12
- path: config.public.directus.loginPath ?? "/login",
13
- query: { redirect: to.path !== "/" ? encodeURIComponent(to.path) : void 0 }
18
+ path: loginPath,
19
+ query: { redirect: to.path !== homePath ? encodeURIComponent(to.path) : void 0 }
14
20
  });
15
21
  }
16
22
  });
@@ -1,15 +1,23 @@
1
- import { addRouteMiddleware, defineNuxtPlugin, refreshNuxtData, useRoute, useRuntimeConfig } from "#app";
1
+ import { defineNuxtPlugin, refreshNuxtData, useRoute, useRuntimeConfig } from "#app";
2
2
  import { apply, remove } from "@directus/visual-editing";
3
3
  import { useDirectusAuth } from "./composables/auth.js";
4
4
  import { useDirectus } from "./composables/directus.js";
5
5
  import { isVisualEditorPage } from "./composables/preview.js";
6
- import auth from "./middleware/auth.js";
6
+ import { useDirectusTokens } from "./composables/tokens.js";
7
7
  export default defineNuxtPlugin(async (nuxtApp) => {
8
8
  const route = useRoute();
9
9
  const config = useRuntimeConfig();
10
+ const tokens = useDirectusTokens();
11
+ const directusAuth = useDirectusAuth();
10
12
  const preview = route.query.preview && route.query.preview === "true";
11
13
  const token = route.query.token;
12
14
  const livePreview = isVisualEditorPage(route);
15
+ if (!tokens.directusUrl.value || tokens.directusUrl.value !== config.public.directus.url) {
16
+ tokens.directusUrl.value = config.public.directus.url;
17
+ if (tokens.accessToken.value || tokens.refreshToken.value) {
18
+ await directusAuth.logout();
19
+ }
20
+ }
13
21
  if (preview && token) {
14
22
  useDirectus().setToken(token);
15
23
  nuxtApp.hook("page:finish", () => {
@@ -29,8 +37,8 @@ export default defineNuxtPlugin(async (nuxtApp) => {
29
37
  });
30
38
  }
31
39
  async function fetchUser() {
32
- if (config.public.directus.fetchUser)
33
- await useDirectusAuth().readMe();
40
+ if (config.public.directus.auth?.enabled ?? true)
41
+ await directusAuth.readMe();
34
42
  }
35
43
  await fetchUser();
36
44
  let loadedUser = false;
@@ -40,5 +48,4 @@ export default defineNuxtPlugin(async (nuxtApp) => {
40
48
  loadedUser = true;
41
49
  }
42
50
  });
43
- addRouteMiddleware("auth", auth);
44
51
  });
@@ -3,7 +3,7 @@ import { authentication, createDirectus, rest } from "@directus/sdk";
3
3
  import { getCookie } from "h3";
4
4
  import { useUrl } from "../../utils/index.js";
5
5
  export function useDirectusAccessToken(event) {
6
- return getCookie(event, useRuntimeConfig().public.directus.cookieNameAccessToken);
6
+ return getCookie(event, useRuntimeConfig().public.directus.auth?.cookies?.accessToken ?? "directus_access_token");
7
7
  }
8
8
  export function useDirectusUrl(path = "") {
9
9
  return useUrl(useRuntimeConfig().public.directus.url, path);
@@ -15,7 +15,7 @@ export async function generateTypes(options) {
15
15
  const name = collection.collection;
16
16
  const typeName = name.startsWith("directus_") ? pascalCase(name) : pascalCase(`${options.prefix}${name}`);
17
17
  const isSingleton = collection.meta?.singleton === true;
18
- types += `export type ${typeName} = {
18
+ types += `interface ${typeName} {
19
19
  `;
20
20
  collection.fields.forEach((field) => {
21
21
  if (field.meta?.interface?.startsWith("presentation-"))
@@ -36,20 +36,8 @@ export async function generateTypes(options) {
36
36
  return item.startsWith("directus_users") || !item.startsWith("directus_");
37
37
  }));
38
38
  return `
39
- declare module '#app' {
40
- ${types.replaceAll("export type", "type")}
41
-
42
- interface AllDirectusCollections {
43
- ${allTypes}
44
- };
45
-
46
- interface DirectusSchema {
47
- ${schemaTypes}
48
- };
49
- }
50
-
51
39
  declare global {
52
- ${types.replaceAll("export type", "type")}
40
+ ${types}
53
41
 
54
42
  interface AllDirectusCollections {
55
43
  ${allTypes}
@@ -102,11 +90,9 @@ async function getCollections(options) {
102
90
  const relations = await directus.request(readRelations());
103
91
  relations?.forEach((relation) => {
104
92
  if (!relation.meta) {
105
- warn(`Not yet implemented: Relation on field '${relation.field}' in collection '${relation.collection}' has no meta. Maybe missing a relation inside directus_relations table.`);
106
93
  return;
107
94
  }
108
95
  if (!relation.meta.one_collection) {
109
- warn("Not yet implemented: Missing one collection");
110
96
  return;
111
97
  }
112
98
  const oneField = collections[relation.meta.one_collection]?.fields.find((field) => field.field === relation.meta.one_field);
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "nuxt-directus-sdk",
3
3
  "type": "module",
4
- "version": "2.1.4",
4
+ "version": "3.0.0",
5
5
  "description": "A Directus nuxt module that uses the Directus SDK",
6
6
  "author": "Matthew Rollinson <matt@rolley.io>",
7
7
  "license": "MIT",