Git Product home page Git Product logo

nuxt-directus's People

Contributors

amerkay avatar atinux avatar casualmatt avatar codiam avatar craigharman avatar danielroe avatar danielwinkelmann avatar dependabot[bot] avatar dochoss avatar docloulou avatar drennvinn avatar dwaring87 avatar florianjs avatar forge-oscar-caballero avatar halwesit avatar happy-turtle avatar intevel avatar jeremio avatar mklueh avatar nainterceptor avatar nmathar avatar ranseur92 avatar rashidpathiyil avatar renovate-bot avatar renovate[bot] avatar sandros94 avatar scherii avatar vaddenz avatar xnacly avatar ymilhahn avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

nuxt-directus's Issues

token is exposed when requesting images

Version

nuxt-directus 3.2.2
nuxt: 3.0.0

Issue

When using const { getThumbnail } = useDirectusFiles(); and getting the image via getThumbnail(image, { ... }) and inserting it in a <img :src="getThumbnail(image, { ... })">, I have recognized, that the directus token is appended to the url inside the rendered <img> tag.

Isn’t that a security problem? I am using a token in order to prevent public access to my API.

Get and Store users SSO tokens

My users connect with Twitch SSO and not login password, I want to know if it's possible to have an equivalent of the login function to get the token and store it directly with nuxt-directus

It seems not avalaible at time, maybe I didn't find it, if it is, adding an example in doc could be a good idea.

Is there a way to store user and token, like a workaround or anything ?

Thanks a lot for this module again

Discussed in #114

Originally posted by geoffreyparrier March 2, 2023
Hi, I have a directus where my users connect with Twitch SSO and I don't know how I can handle their token, where and how to set the user to use the other functionalities of nuxt-directus ?

In the future, could we have a function to handle it automatically ?

Thanks for this great module

[request error] [unhandled] [500] nuxt instance unavailable in pinia store

Version

nuxt-directus 3.2.2
nuxt: 3.0.0-rc.13

Steps to reproduce

use the useDirectus methods inside a pinia store...

What is Expected?

for it to work

What is actually happening?

pinia apparently does not have access to the nuxt instance. This is unfortunate as I would mainly like to use useDirectus inside my pinia store. Not sure if this is something you can fix, but wantesd to make really sure that this is not possible or if I'm doing something wrong.

Nuxt server startup issue - Cannot read property 'public' of undefined

Version

nuxt-directus: 3.0.3
"@nuxt/bridge": "0.10.1",
"@nuxt/bridge-edge": "3.0.0-27296423.f3082ca",
"nuxt-edge": "2.16.0-27300977.ab1c6cb4",

Reproduction Link

https://codesandbox.io/s/nuxt-bridge-directus-module-problem-tklbm2?file=/nuxt.config.js

Steps to reproduce

  1. Add directus as a dependency.
  2. Set up directus in nuxt.config.js according to docs.
  modules: ["nuxt-directus"],
  directus: {
    url: "http://localhost:8055",
    fetchUserParams: {
      fields: ["*", "djs.*"]
    },
    autoFetch: true
  }
  1. Run dev server.

What is Expected?

Dev server starts.

What is actually happening?

There is an error:

Cannot read property 'public' of undefined 
  at setup (node_modules/nuxt-directus/dist/module.mjs:53:32)
  at ModuleContainer.normalizedModule (node_modules/nuxt-directus/node_modules/@nuxt/kit/dist/index.mjs:637:29)
  at async ModuleContainer.addModule (node_modules/@nuxt/core-edge/dist/core.js:174:20)
  at async ModuleContainer.ready (node_modules/@nuxt/core-edge/dist/core.js:47:5)
  at async Nuxt._init (node_modules/@nuxt/core-edge/dist/core.js:346:5)

Additional info

It seems like nuxt-directus is expecting this to be in the nuxt.config.js:

runtimeConfig: {
   public: {}
}

When I add this to the nuxt.config.js (empty public object), server starts, but then there is a different error when app is loaded in the browser:

[nuxt] [request error] Cannot read properties of undefined (reading 'autoFetch')
  at ./.nuxt/dist/server/server.js:13441:23  
  at callWithNuxt (./.nuxt/dist/server/server.js:8196:20)  
  at ./.nuxt/dist/server/server.js:8206:26  
  at createApp (./.nuxt/dist/server/server.js:1701:87)  
  at async module.exports../.nuxt/server.js.__webpack_exports__.default (./.nuxt/dist/server/server.js:4303:7)  
  at async Object.renderToString (./node_modules/vue-bundle-renderer/dist/runtime.mjs:172:19)  
  at async ./.nuxt/dev/index.mjs:533:21  
  at async ./.nuxt/dev/index.mjs:107:22  
  at async ./node_modules/h3/dist/index.mjs:592:19  
  at async Server.nodeHandler (./node_modules/h3/dist/index.mjs:538:7)

getItemById returns undefined

Version

Directus 9.10.0
nuxt-directus 2.0.0
nuxt: 3.0.0-rc.3

Reproduction Link

This commit: 2ef29ce broke this method functionality.
The only thing wrong before was the typing, it already returned a single item.

This line now returns undefined:

return items.data[0]; // should be return items.data;

bug on auth

I am developing a little project based on nuxt 3 and Directus.

There is a problem when i'm trying to login logout. When i call login method, the user is fetch and setted and same for token and when i logout, i have the user and the token as undefined. But when i retry login with other user, the useDirectusUser returns last user and not new one. I don't know why but it's a real problem.

PS/ To avoid the problem and have new user, i have to refresh the page.

Nuxt showing error page on failed login

Version

nuxt-directus 5.1.1
nuxt: 3.3.2

Reproduction Link

Steps to reproduce

Both my Nuxt frontend and Directus backend are running via docker-compose.

<script setup>

const {login} = useDirectusAuth();

const onSubmit = async () => {
    try{
        await login({
            email: "[email protected]",
            password: "notapassword"
        })
    }catch(e){
        console.log("error", e.data);
    }
}
</script>

When the onSubmit method is called the login attempt it made. Directus returns a 401 as the user doesn't exist. Instead of the error being caught by the try catch, the page shows the nuxt error page:
image
image

What is Expected?

The login error to be caught and handled in the try catch.

What is actually happening?

The page is showing the nuxt error page.

Nuxt v3 autoImports:dirs hook is deprecated

Version

nuxt-directus: v3.0.1
nuxt: v3.0.0-rc.9

Steps to reproduce

Install given Nuxt and nuxt-directus versions and Nuxt will warn as soon as you start the Nuxt server:

 WARN  autoImports:dirs hook is deprecated. Use addImportsDir() from @nuxt/kit or imports:dirs with nuxt>=3.0.0-rc.9.

What is Expected?

Expecting auto imports to work.

What is actually happening?

Auto imports don't work.

When refreshing tokens, "refreshToken" is not updated

Version

nuxt-directus: 5.1.1
nuxt: 3.3.2

Reproduction Link

Steps to reproduce

Assuming SSR is enabled

  1. Create an auth middleware
// /middleware/auth.ts
export default defineNuxtRouteMiddleware(async (_to, _from) => {
    const { refreshTokens, refreshToken, token } = useDirectusToken()
    const user = useDirectusUser()

    console.log("token before refresh")
    console.log(token.value)
    console.log(refreshToken.value)
    
    if (!user.value) {
        try {
            console.log("refreshing token")
            const auth = await refreshTokens()
            console.log("refreshing token ok")
            console.log(auth)
            if (auth !== null) {
                console.log("token after refresh")
                console.log(token.value)
                console.log(refreshToken.value)
            }
        } catch {
            // return navigateTo('/login')
        }
    }
})
  1. Login
    Login with a correct email/password. At this stage, the middleware will print something like this
token before refresh                                                                                                                                                                                                                                                 

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNkYmUyYzkyLTc5NzktNDhiZi1hNTlkLTk3YzU1ZTFlODY3MSIsInJvbGUiOiJkN2NkZmZjMC1jNzcwLTRlZjgtODkwZi1kYTcwYmQzOGFmMTYiLCJhcHBfYWNjZXNzIjp0cnVlLCJhZG1pbl9hY2Nlc3MiOmZhbHNlLCJpYXQiOjE2ODAyMDg4MzIsImV4cCI6MTY4MDIwOTczMiwiaXNzIjoiZGlyZWN0dXMifQ.7v0nZuyKTCUoZm0QHBaJP8k_UCTma1wWS3ouovVgGzU ## token

kF3YVuWHpbvQ3GZ60Bizcyw3owD0fgoL2GaIpervHmq_Uq8-vpoLjy_6-6uUrgXg ## refresh token

We can see this in both the server side and client side.

  1. Wait for token to expire
    About 15 minutes by default

  2. Refresh tokens
    Refresh the page, we will see this output on the server

[Directus Error]: Error: Unauthorized ## This is from fetching user at `/me`
                                                                                                                                                                                                                       
token before refresh
                                                                                                                                                                                                                                       
null ## access token is gone because it has expired
                                                                                                                                                                                                                                              
kF3YVuWHpbvQ3GZ60Bizcyw3owD0fgoL2GaIpervHmq_Uq8-vpoLjy_6-6uUrgXg ## this is the refresh token we want to use
                                                                                                                                                                            
refreshing token                                                                                                                                                                                                                                                     
refreshing token ok
                                                                                                                                                                                                                                           
{                                                                                                                                                                                                                                                                    
  access_token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNkYmUyYzkyLTc5NzktNDhiZi1hNTlkLTk3YzU1ZTFlODY3MSIsInJvbGUiOiJkN2NkZmZjMC1jNzcwLTRlZjgtODkwZi1kYTcwYmQzOGFmMTYiLCJhcHBfYWNjZXNzIjp0cnVlLCJhZG1pbl9hY2Nlc3MiOmZhbHNlLCJpYXQiOjE2ODAyMDk4MDksImV4cCI6MTY4MDIxMDcwOSwiaXNzIjoiZGlyZWN0dXMifQ.CULjB_SE3O83t0RER5y-ttO0fCRbIN9pFMv1RPyEdXA',
  expires: 900000,
  refresh_token: 'mnY_zP7xRoOgn3BRrj5_VFiNSaC6YEJ-yIBde7mkkPgO2wd-ZcVBB-9vM79lKmw1'
} ## refresh is successful, with valid new access token and refresh token

token after refresh
                                                                                                                                                                                                             
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNkYmUyYzkyLTc5NzktNDhiZi1hNTlkLTk3YzU1ZTFlODY3MSIsInJvbGUiOiJkN2NkZmZjMC1jNzcwLTRlZjgtODkwZi1kYTcwYmQzOGFmMTYiLCJhcHBfYWNjZXNzIjp0cnVlLCJhZG1pbl9hY2Nlc3MiOmZhbHNlLCJpYXQiOjE2ODAyMDk4MDksImV4cCI6MTY4MDIxMDcwOSwiaXNzIjoiZGlyZWN0dXMifQ.CULjB_SE3O83t0RER5y-ttO0fCRbIN9pFMv1RPyEdXA ## we can see that access_token is updated successfully

mnY_zP7xRoOgn3BRrj5_VFiNSaC6YEJ-yIBde7mkkPgO2wd-ZcVBB-9vM79lKmw1 ## refresh token is also successfully updated

However, we see this in the browser

token before refresh

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNkYmUyYzkyLTc5NzktNDhiZi1hNTlkLTk3YzU1ZTFlODY3MSIsInJvbGUiOiJkN2NkZmZjMC1jNzcwLTRlZjgtODkwZi1kYTcwYmQzOGFmMTYiLCJhcHBfYWNjZXNzIjp0cnVlLCJhZG1pbl9hY2Nlc3MiOmZhbHNlLCJpYXQiOjE2ODAyMDk4MDksImV4cCI6MTY4MDIxMDcwOSwiaXNzIjoiZGlyZWN0dXMifQ.CULjB_SE3O83t0RER5y-ttO0fCRbIN9pFMv1RPyEdXA ## this is the new token

kF3YVuWHpbvQ3GZ60Bizcyw3owD0fgoL2GaIpervHmq_Uq8-vpoLjy_6-6uUrgXg ## this is the old refresh token
  1. Refresh the page again
    We see this output on the server
token before refresh

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjNkYmUyYzkyLTc5NzktNDhiZi1hNTlkLTk3YzU1ZTFlODY3MSIsInJvbGUiOiJkN2NkZmZjMC1jNzcwLTRlZjgtODkwZi1kYTcwYmQzOGFmMTYiLCJhcHBfYWNjZXNzIjp0cnVlLCJhZG1pbl9hY2Nlc3MiOmZhbHNlLCJpYXQiOjE2ODAyMDk4MDksImV4cCI6MTY4MDIxMDcwOSwiaXNzIjoiZGlyZWN0dXMifQ.CULjB_SE3O83t0RER5y-ttO0fCRbIN9pFMv1RPyEdXA ## this is the new token
                                                                                                                                                                                                                                                             
kF3YVuWHpbvQ3GZ60Bizcyw3owD0fgoL2GaIpervHmq_Uq8-vpoLjy_6-6uUrgXg ## this is the old refresh token

The client side has the same output. So we are in the state where we have a valid access token, but an invalid refresh token.

  1. Wait for the token to expire to refresh
    When the access token expires, an attempt to refresh will be made, but we only have the invalid refresh token to work with, and the refresh will fail.

What is Expected?

Refresh token stays after a successful update.

What is actually happening?

The new refresh token is missing. The old one is still in place.

Nuxt2 integration?

Hi, great module! Do you think it would be possible to use it on Nuxt2 without Bridge?

Thanks!

useAsyncData example for static generation

How one would use directus API to generate a completely static site using Nuxt3? Simple html/js files that do not trigger backend requests.

I'm trying to implement the following:

export const asyncDirectusItems = async (key, config, transform) => {
  const { getItems } = useDirectusItems();
  const { data } = await useAsyncData(key, async () => await getItems(config), {transform});
  return data;
};

export const asyncDirectusItemById = async (collection, id, transform) => {
  const { getItemById } = useDirectusItems();
  const key = `${collection}#${id}`;
  const { data } = await useAsyncData(key, async () => await getItemById({ collection, id }), {transform});
  return data;
};

But recent Nuxt 3 RC's (9 and 12) either fail to generate directly accessible SSR pages or mix their markup with the front page. Also I'm having trouble to prevent Directus API calls (which are unnecessary for a completely static website).

<script setup>
const categories = await asyncDirectusItems('blog_categories', {
  collection: "Blog",
  params: {
    fields: "category",
    groupBy: "category"
  }
});

const posts = await asyncDirectusItems('published_blogs', {
  collection: "Blog",
  params: {
    filter: {
      status: "published"
    }
  }
});
</script>
```html

2 or more instances of Directus query on one website with nuxt-directus …

Is your feature request related to a problem? Please describe.

We have 2 different servers, each with a Directus account. Example news and events. On one website we want to make 2 queries, on both servers. We use nuxt 3 to build up the frontpage. We want to use the nuxt-directus plugin, to get the data from the 2 instances …

The website needs two querys:

The news
The events

Is it possible to do this with the nuxt-directus module???
If yes, how? (Where is the documentation?)

Of course there can be 2 different authorizations and so on …

Describe the solution you'd like

I would like to have an array of arguments, to make more nuxt-directus instances … or to make an array of urls to connect with … to get the data from there …

Describe alternatives you've considered

I don't have an alternate solution … Or to get the data from apollo … (but then, why using directus and not PostGreS directly???

Additional context

Not now …

getItemById return an array of items

Version

nuxt-directus 1.8.0
nuxt: 3.0.0-rc.1

Reproduction Link

image

What is Expected?

Expect to get only one item when using getItemById and providing collection + id.

What is actually happening?

The request is working but return an array of items for Typescript which cause intellisense problems.

Auth middleware useDirectusUser is undefined

nuxt-directus 1.1.4
nuxt: 3.0.0-27478897.169aa35

Steps to reproduce

  1. Create page /login.vue
  2. Create page /index.vue and add
definePageMeta({
  middleware: ["auth"]
})
  1. Add middleware /middleware/auth.ts
// /middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {
  const user = useDirectusUser()

  if (!user.value) {
    return navigateTo("/login")
  }
})

What is Expected?

Using const { login } = useDirectusAuth(); I should be able to sign in, refresh the page and stay signed in, as user.value is still defined.

What is actually happening?

On refresh, the middleware kicks in again and this time returns user.value as undefined and redirects me to /login. Even though user.value is still defined.

Workaround

Using useDirectusToken()seems to stay defined, and can be used as a workaround for auth middleware.

// /middleware/auth.ts
export default defineNuxtRouteMiddleware((to, from) => {
  const token = useDirectusToken()

  if (!token.value) {
    return navigateTo("/login")
  }
})

useDirectusFiles 500 useDirectus is not defined

Version

nuxt-directus 1.7.1
nuxt: 3.0.0-rc.1

Reproduction Link

Steps to reproduce

When add const { getThumbnail } = useDirectusFiles(); to <script setup>

<script setup>
const { getItems } = useDirectusItems();
const { getThumbnail } = useDirectusFiles();

const posts = await getItems({ collection: "web_post" });
</script>

Shows the error
image

What is Expected?

I tried other useXXX doesn't cause the error. Don't know how to correctly use useDirectusFiles.

What is actually happening?

information from "meta"

hi, I'm trying to access the "meta" information through "getItems", I had a look at the documentation but I couldn't find anything related

Cannot login when static token is revoked/deleted.

Version

nuxt-directus: v3.2.2
nuxt: v3.2.0

Reproduction Link

Not Applicable

Steps to reproduce

  1. Add a revoked static token to nuxt.config.js
  2. Try to login using useDirectusAuth() using correct credentials

What is Expected?

To be able to login.

What is actually happening?

Getting Invalid Credentials error since the token is revoked but is forgotten inside the nuxt.config.js

Final notes

We really should be able to have a boolean argument in the composables that decides if we want to use the nuxt config token or not.

At the moment it causes all kinds of bugs:

  1. Firstly, the above bug. If someone removes or regenerates the static token from the Directus admin page, then not only does that user associated with the static token (Usually the website token) loses access to everything, but even legitimate users can't login.
  2. I want to keep the granular permissions of each user in order for the to achieve the multi-tenancy inside the Admin page but I would like my application/website to be able to view/show all collections available to them. Currently, if I use the token to view a collection but then someone logs in successfully the static token, which was for the application is forgotten and I now lose access to everything. Currently If I need to have access to everything from the website but still allow users to use the Directus Auth, I have to do 2 entirely different implementations to disable the override of the static token or create a new set of Composables that ignore the use the static token based on a boolean value.

Add an update user method

Is your feature request related to a problem? Please describe.

Besides the createUser({ ... }) method, I think there should be an updateUser({ ... }) method that updates the current user.

Describe the solution you'd like

N/A

Describe alternatives you've considered

N/A

Additional context

N/A

Unclear how to authenticate

Hello,

So the documentation says

image

However, I'm getting 403 errors, as I'm not authenticated and I have not seen anything clear in the docs on how to specify an access token to my directus backend.

I generally only want to fetch content during the build phase to render static content. How would I do that?

500 meta not defined

Error on initial load

Version

nuxt-directus 3.0.1
nuxt: Nuxt 3.0.0-rc.9

As was discussed over discord

Global Query Parameters are not applied

Version

nuxt-directus 1.3.0
nuxt: 3.0.0-27489614.315e5b5

Reproduction Link

https://github.com/jjaimealeman/nuxt3-directus-blog/tree/main/nuxt3-directus-blog

What is Expected?

The module should call endpoint: https://mccz9cp7.directus.app/items/blog?filter=%7B%20%22title_slug%22:%20%22first-commit%22%20%7D
The applied filters

What is actually happening?

It calls https://mccz9cp7.directus.app/items/blog/first-commit

Thanks to @jjaimealeman for reporting this.

Require NUXT_DIRECTUS_URL in .env

Version

nuxt-directus v2.0.0
nuxt: 3.0.0-rc1

Steps to reproduce

Add a runtime config to nuxt.config.ts. This then requires that the directus config object is moved from the root to the runtime config to access the config.directus.url object.

runtimeConfig: {
		public: {
			directusEmail: "",
			directusPassword: "",
		},
		directus: {
			url: "",
		},
	},

However if you do this following the set up procedure the config object then looks like this:

{
  app: { baseURL: '/', buildAssetsDir: '/_nuxt/', cdnURL: '' },
  nitro: { routes: {}, envPrefix: 'NUXT_' },
  public: { directusEmail: '[email protected]', directusPassword: 'password' },
  directus: { url: '' }
}

Note the empty directus URL despite having DIRECTUS_URL in .env file.
Adding NUXT_DIRECTUS_URL to the .env file fixes this issue.

Also note that if you remove DIRECTUS_URL nuxt-directive gives an error:

Cannot start nuxt: Missing DIRECTUS_URL in .env

So you now have 2x .env variables for the same thing.

What is Expected?

Should not require NUXT_DIRECTUS_URL and it should be available in the runtime config.

What is actually happening?

Require NUXT_DIRECTUS_URL in .env otherwise nuxt-directus cannot contact the Directus server.

[nuxt] [request error] nuxt instance unavailable - from composables/news.vue

npx nuxi info
Nuxt CLI v3.0.0-rc.4-27588443.cf25525                                 20:02:49
RootDir: /home/hermes/projetos/nuxt/araripina           20:02:50
Nuxt project info:                                                    20:02:50

------------------------------
- Operating System: `Linux`
- Node Version:     `v16.14.2`
- Nuxt Version:     `3.0.0-rc.4-27588443.cf25525`
- Package Manager:  `[email protected]`
- Builder:          `vite`
- User Config:      `modules`, `directus`, `head`, `build`, `publicRuntimeConfig`
- Runtime Modules:  `@nuxtjs/[email protected]`, `[email protected]`
- Build Modules:    `-`
------------------------------

I'm using the nuxt-directus module inside composables file, like this:
const { getItemById } = useDirectusItems()

Show me this error:

[nuxt] [request error] nuxt instance unavailable
  at Module.useNuxtApp (./.nuxt/dist/server/server.mjs:458:13)  
  at Module.useDirectus (./.nuxt/dist/server/server.mjs:7541:38)  
  at Module.useDirectusItems (./.nuxt/dist/server/server.mjs:7449:42)  
  at $id_caa1d2fd (./.nuxt/dist/server/server.mjs:7410:47)  
  at async __instantiateModule__ (./.nuxt/dist/server/server.mjs:14298:3)

I cant to use this module inside composable/news.vue ? However, may i to use just inside <script setup>?

global query "deep" non supported

Version

nuxt-directus 1.5.0
nuxt: v3.0.0-27491748.3186841

Reproduction Link

If you pass those parameters to the SDK, it will not stringify the deep, but only the filter.

fields:[
  "*",
  "invoices.number",
  "invoices.id",
  "invoices.total",
  "invoices.hosted_invoice_url",
  "invoices.status",
  "subscriptions.id",
  "subscriptions.status",
  "subscriptions.metadata_title"
],
deep:[
  {
    "invoices":{
      "_limit":3,
      "_sort":"-created",
    }
  }
]

What is Expected?

that all the Global Query Parameters are supported, because i think that [Aggregation & Grouping](Aggregation & Grouping) could have the same issue been a complicated object.

What is actually happening?

The call made to the server have deep=[object+Object] as one of his parameters.

update for deprecated addAutoImportDir in Nuxt 3

Version

nuxt-directus: 3.2.1
nuxt: 3.0.0

Steps to reproduce

Install new fresh Nuxt 3:
npx nuxi init nuxt-app

then install nuxt-directus with the config
npm i nuxt-directus

then run the dev server
npm run dev

What is Expected?

Nuxt run the dev server with nuxt-directus seamlessly

What is actually happening?

Glad to see the stable version of Nuxt 3, but seems some modules need update to suit the stable version.
I'm try to running stable version of Nuxt 3 with nuxt-directus module but seems like there is import changes in stable version nuxt/framework#9029.

When try to run dev server the console warn me an error :
Error while requiring module nuxt-directus: SyntaxError: The requested module '@nuxt/kit' does not provide an export named 'addAutoImportDir'
while i think the PR of #85 should fix this, but when i'm trying change the module manually in node_modules the console warn me :
image

Using typescript directus SDK

Hello there,

This plugin has a nice integration with nuxt, but I'm wondering why don't use default Directus SDK which provide a powerful typescript integration.

It can be simply done by creating a custom Storage class, here is a working sample:

import { Directus, BaseStorage } from '@directus/sdk'
import type { NuxtApp } from '#app'

export function useDirectusSdk<T = Record<string, any>>() {
  const nuxtApp = useNuxtApp()
  const config = useRuntimeConfig()
  return new Directus<T>(config.public.directus.url, {
    storage: new CookieStorage(nuxtApp),
    auth: {
      mode: 'cookie',
      autoRefresh: !process.server,
    },
  })
}

class CookieStorage extends BaseStorage {
  nuxtApp: NuxtApp

  constructor(nuxtApp: NuxtApp) {
    super()
    this.nuxtApp = nuxtApp
  }

  get(key: string) {
    this.nuxtApp._cookies = this.nuxtApp._cookies || {}
    if (key in this.nuxtApp._cookies) {
      return this.nuxtApp._cookies[key].value
    }

    const cookie = useCookie<string | null>(key)
    this.nuxtApp._cookies[key] = cookie

    return cookie.value
  }
  set(key: string, value: string) {
    this.nuxtApp._cookies = this.nuxtApp._cookies || {}
    if (key in this.nuxtApp._cookies) {
      this.nuxtApp._cookies[key].value = value
      return this.nuxtApp._cookies[key].value
    }

    const cookie = useCookie<string | null>(key)
    cookie.value = value
    this.nuxtApp._cookies[key] = cookie

    return cookie.value
  }
  delete(key: string) {
    this.nuxtApp._cookies = this.nuxtApp._cookies || {}
    if (key in this.nuxtApp._cookies) {
      const value = this.nuxtApp._cookies[key].value
      this.nuxtApp._cookies[key].value = null
      return value
    }

    const cookie = useCookie<string | null>(key)
    const value = cookie.value
    cookie.value = null
    this.nuxtApp._cookies[key] = cookie

    return value
  }
}

Usage would be same as official sdk:

// this can be generated 
interface CustomDirectusTypes {
  // ...
  directus_activity: DirectusActivity;
  directus_collections: DirectusCollections;
  // ...
}

const directus = useDirectusSdk<CustomDirectusTypes>()

That would solve typescript and errors managements issues that this module introduces regarding this SDK

We could go further by integrating a custom Transport layer to use fetch (via oh-my-fetch) instead of axios.
But this should be optional, since using axios is the default behavior of the SDK. It also allows having upload progress, which we can not have with fetch.

Cors Error with module

Hello im using your module in my Nuxt 3 application and have the current configurations

directus: {
url: process.env.DIRECTUS_URL,
auth: {
email: process.env.DIRECTUS_EMAIL,
password: process.env.DIRECTUS_PASSWORD,
token: process.env.DIRECTUS_TOKEN,
}
},

in my env file:

DIRECTUS_URL='http://example.com:8055/'
DIRECTUS_TOKEN='-'
DIRECTUS_EMAIL=[email protected]
DIRECTUS_PASSWORD=Example@password //not real credentials just an example for the env.

cors error in dev console:

Access to fetch at http://example.com:8055 from origin 'http://localhost:3011' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I have selected all of my collections to have read access

Any idea what could be happening here?

Use access_token authentication method

Is your feature request related to a problem? Please describe.

You currently can't use the Directus access token method to authenticate to the API.
Ie. I share the "token" from the User > Admin Settings section and provide that in the Query String or the Authorization Bearer header.

Describe the solution you'd like

login should accept a {"token" OR { email: string, password: string }

<script setup lang="ts">
const { login } = useDirectusAuth();
const router = useRouter();

const onSubmit = async () => {
  try {
    await login({ token: "" });
  } catch (e) {}
};
</script>

useDirectusAuth - unsuccessful login throws type error

Version

nuxt-directus 2.1.0
nuxt: [email protected]

Steps to reproduce

  1. Try to login to Directus server using wrong credentials.
  2. Nuxt-Directus throws an error:
TypeError: Cannot read properties of undefined (reading 'data')
    at _callee2$ (useDirectusAuth.mjs:47:23)
    at tryCatch (runtime.js:63:15)
    at Generator.invoke [as _invoke] (runtime.js:294:1)
    at Generator.next (runtime.js:119:1)
    at asyncGeneratorStep (asyncToGenerator.js:3:1)
    at _next (asyncToGenerator.js:25:1)

The code that throws an error is here > line with setToken(response.data.access_token):

  const login = async (data) => {
    setToken(null);
    const response = await directus("/auth/login", {
      method: "POST",
      body: data
    });
    setToken(response.data.access_token);
    const user2 = await fetchUser();
    return {
      user: user2,
      access_token: response.data.access_token,
      expires: response.data.expires
    };
  };

What is Expected?

Module returns the error response returned from the server and doesn't throw it's own type error.

getThumbnail - TypeError: Failed to construct 'URL': Invalid URL

Version

nuxt-directus : 5.0.1
nuxt : 3.2.3

Steps to reproduce

Simply :

<img :src="img(fileId)">
const fileId = "b40911b1-e4e0-4fc0-a080-21b85ed921ff";
const { getFiles, getThumbnail: img } = useDirectusFiles();

What is Expected?

Show image.

What is actually happening?

Uncaught (in promise) TypeError: Failed to construct 'URL': Invalid URL
    at Proxy.getThumbnail (useDirectusFiles.mjs?v=4eb507e2:24:17)

In :

const getThumbnail = (fileId, options) => {
    const url = new URL(`${directusUrl}assets/${fileId}`); <---

Another question, how to use getFiles to v-bind= file like video/mp4 from Directus ?

Thanks ! :)

CORS error

Version

nuxt-directus: 3.2.2
nuxt: 3.0.0

Steps to reproduce

Hi, I'm just trying to use this plugin and whatever I do I keep getting a CORS error on login. My server settings are fine and I can manually do the request with useFetch (/auth/login) with no issues.

Whenever I use the internal login function I get the error. Both locally and when deployed to a test machine.

Access to fetch at 'https://domain/auth/login' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field authorization is not allowed by Access-Control-Allow-Headers in preflight response.

POST https://domain/auth/login net::ERR_FAILED

I thought it was a server error but it's not...

config['directus'] to config.public['directus']

Version

nuxt: 3.4.0
nuxt-directus: 5.1.1

What’s happening

The usual directus config now issues a warning:
[runtimeConfig] You are trying to access a public runtime config value (directus) directly from the top level. This currently works (for backward compatibility with Nuxt 2) but this compatibility layer will be removed in v3.5. Instead, you can update config['directus'] to config.public['directus'].

This happens regardless if directus url (and token) is configured top level or inside runtime config

export default defineNuxtConfig({
  directus: { url: ##, token: ## },
  runtimeConfig: {
    public: { 
      directus: { url: ##, token: ## }
    }
  }
})

Include metadata of getItems query

Hi,

I'm not sure what is the best way to implement this but I think meta data is needed for paging when quering a set of data.

How did you guys handle this right now?

Auth tokens not refreshed.

nuxt-directus
nuxt:

Steps to reproduce

Use nuxt-directus to login and issue API requests. These requests will start to fail when the Auth token_expires.

Directus default token expiry is 15 minutes with a refresh_token validity of 7 days. nuxt-directus does not appear to have any support for handling expired tokens.

There is a PR #45 which does not appear to work either.

Dependency Dashboard

This issue lists Renovate updates and detected dependencies. Read the Dependency Dashboard docs to learn more.

This repository currently has no open or pending branches.

Detected dependencies

github-actions
.github/workflows/ci.yml
  • actions/setup-node v3
  • actions/cache v3
npm
docs/package.json
  • @nuxt/content-theme-docs ^0.11.1
  • nuxt ^2.15.8
  • vue-plausible ^1.3.2
package.json
  • @nuxt/kit ^3.0.0-rc.13
  • standard-version ^9.3.2
  • nuxt ^3.0.0-rc.13
playground/package.json

  • Check this box to trigger a request for Renovate to run again on this repository

useDirectusUsers is not on npm

Version

nuxt-directus: 3.2.2
nuxt: 3.1.1

Reproduction Link

The composable is not included in the release.
Please release a new version

Steps to reproduce

What is Expected?

To be included and available

What is actually happening?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.