Skip to content

Commit

Permalink
fix: return response on Errors, fixed linting
Browse files Browse the repository at this point in the history
  • Loading branch information
Intevel committed Apr 26, 2023
1 parent 21f542d commit ac5fd4e
Show file tree
Hide file tree
Showing 5 changed files with 40 additions and 54 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
],
"scripts": {
"prepack": "nuxt-module-build",
"dev": "nuxi dev playground PORT='3001'",
"dev": "nuxi dev playground",
"dev:build": "nuxi build playground",
"dev:prepare": "nuxt-module-build --stub && nuxi prepare playground",
"docs": "cd docs && pnpm dev",
Expand Down
14 changes: 3 additions & 11 deletions playground/app.vue
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,6 @@
<button style="margin-top: 25px" @click="logUser">
Log User
</button>
<div style="margin-top: 25px">
<img
:src="img(fileId, { width: 300, height: 300, fit: 'cover' })"
alt="square thumbnail"
>
<img :src="img(fileId, { width: 300, format: 'webp' })" alt="webp">
</div>

<div>
<!-- User Composable Tests -->
Expand Down Expand Up @@ -59,8 +52,7 @@ const user = useDirectusUser()
const { getItems, getItemById, createItems, deleteItems } = useDirectusItems()
const { getCollections } = useDirectusCollections()
const router = useRouter()
const fileId = 'da8e7c7b-d115-40cd-a88c-d4aedd7eea6c'
const { getThumbnail: img } = useDirectusFiles()
const { token } = useDirectusToken()
const {
createUsers,
Expand All @@ -83,12 +75,12 @@ const onSubmit = async () => {
try {
await login({
email: 'admin@example.com',
password: 'CUUpF9TkMg3o'
password: 'd1r3ctu5'
})
router.push('/authenticated-page')
} catch (e) {
console.log(e.data)
console.log(e)
}
}
Expand Down
43 changes: 22 additions & 21 deletions src/runtime/composables/useDirectus.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import type { NitroFetchOptions } from 'nitropack';
import { useRuntimeConfig, createError } from "#app";
import { useDirectusUrl } from "./useDirectusUrl";
import { useDirectusToken } from "./useDirectusToken";
import type { NitroFetchOptions } from 'nitropack'
import { useRuntimeConfig, createError } from '#app'
import { useDirectusUrl } from './useDirectusUrl'
import { useDirectusToken } from './useDirectusToken'

export const useDirectus = () => {
const baseURL = useDirectusUrl();
const config = useRuntimeConfig();
const { token } = useDirectusToken();
const baseURL = useDirectusUrl()
const config = useRuntimeConfig()
const { token } = useDirectusToken()

return async <T>(
url: string,
fetchOptions: NitroFetchOptions<string> = {},
useStaticToken = true
): Promise<T> => {
const headers: HeadersInit = {};
const headers: HeadersInit = {}

if (token && token.value) {
headers.Authorization = `Bearer ${token.value}`;
headers.Authorization = `Bearer ${token.value}`
} else if (config.public.directus.token && useStaticToken) {
headers.Authorization = `Bearer ${config.public.directus.token}`;
headers.Authorization = `Bearer ${config.public.directus.token}`
}

try {
Expand All @@ -27,24 +27,25 @@ export const useDirectus = () => {
...fetchOptions,
headers: {
...headers,
...fetchOptions.headers,
},
});
...fetchOptions.headers
}
})
} catch (err: any) {
if (process.dev) {
console.error("[Directus Error]: " + err);
console.error('[Directus Error]: ' + err)
console.log(err.response._data)
} else {
console.error(
"[Directus Error]: " +
'[Directus Error]: ' +
err.response?.status +
", " +
', ' +
err.response?.statusText
);
)
}
throw createError({
statusCode: err.response?.status,
statusMessage: err.response?.statusText,
});
statusMessage: err.response?._data
})
}
};
};
}
}
33 changes: 13 additions & 20 deletions src/runtime/composables/useDirectusAuth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,30 +10,24 @@ import type {
} from '../types'
import { useDirectus } from './useDirectus'
import { useDirectusUser } from './useDirectusUser'
import { useDirectusUrl } from './useDirectusUrl'
import { useDirectusToken } from './useDirectusToken'

export const useDirectusAuth = () => {
const url = useDirectusUrl()
const config = useRuntimeConfig()
const directus = useDirectus()
const user = useDirectusUser()
const { token, refreshToken, expires } = useDirectusToken()

const setToken = (value: string | null, _refreshToken?: string | null, _expires?: number | null) => {
token.value = value

if (value === null) {
expires.value = null
refreshToken.value = null
}
const setAuthCookies = (_token: string, _refreshToken: string, _expires: number) => {
token.value = _token
refreshToken.value = _refreshToken
expires.value = _expires
}

if (_refreshToken) {
refreshToken.value = _refreshToken
if (_expires) {
expires.value = _expires
}
}
const removeTokens = () => {
token.value = null
expires.value = null
refreshToken.value = null
}

const setUser = (value: DirectusUser) => {
Expand Down Expand Up @@ -63,7 +57,7 @@ export const useDirectusAuth = () => {
setUser(res.data)
}
} catch (e) {
setToken(null)
console.error("Couldn't fetch user", e)
}
}
return user
Expand All @@ -73,7 +67,7 @@ export const useDirectusAuth = () => {
data: DirectusAuthCredentials,
useStaticToken?: boolean
): Promise<DirectusAuthResponse> => {
setToken(null)
removeTokens()

const response: { data: DirectusAuthResponse } = await directus(
'/auth/login',
Expand All @@ -85,7 +79,7 @@ export const useDirectusAuth = () => {
)

if (!response.data.access_token) { throw new Error('Login failed, please check your credentials.') }
setToken(response.data.access_token, response.data.refresh_token, response.data.expires)
setAuthCookies(response.data.access_token, response.data.refresh_token, response.data.expires)

const user = await fetchUser()

Expand Down Expand Up @@ -140,13 +134,12 @@ export const useDirectusAuth = () => {
method: 'POST',
body: { refresh_token: refreshToken.value }
})
setToken(null, null, null)
removeTokens()
setUser(null)
await fetchUser()
}

return {
setToken,
setUser,
fetchUser,
login,
Expand Down
2 changes: 1 addition & 1 deletion src/runtime/plugin.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import { useDirectusAuth } from './composables/useDirectusAuth'
import { defineNuxtPlugin, useRuntimeConfig } from '#app'
import { useDirectusAuth } from './composables/useDirectusAuth'

export default defineNuxtPlugin(async (nuxtApp) => {
const config = useRuntimeConfig()
Expand Down

0 comments on commit ac5fd4e

Please sign in to comment.