From 16af8317b61dbd56dde7b5f5308269f4a033ec6c Mon Sep 17 00:00:00 2001 From: Eduardo San Martin Morote Date: Wed, 14 Aug 2024 15:02:01 +0200 Subject: [PATCH] feat: experimental auto export of data loaders --- package.json | 1 + playground/src/loaders/colada-loaders.ts | 37 +++ playground/src/loaders/todos.ts | 0 .../src/pages/users/colada-loader.[id].vue | 44 +--- playground/vite.config.ts | 1 + pnpm-lock.yaml | 17 +- src/data-loaders/auto-exports.ts | 64 ++++++ src/data-loaders/navigation-guard.ts | 7 + src/index.ts | 216 +++++++++--------- src/options.ts | 14 ++ 10 files changed, 242 insertions(+), 159 deletions(-) create mode 100644 playground/src/loaders/colada-loaders.ts create mode 100644 playground/src/loaders/todos.ts create mode 100644 src/data-loaders/auto-exports.ts diff --git a/package.json b/package.json index 8d91b2662..fb777287c 100644 --- a/package.json +++ b/package.json @@ -172,6 +172,7 @@ "fast-glob": "^3.3.2", "json5": "^2.2.3", "local-pkg": "^0.5.0", + "magic-string": "^0.30.11", "mlly": "^1.7.1", "pathe": "^1.1.2", "scule": "^1.3.0", diff --git a/playground/src/loaders/colada-loaders.ts b/playground/src/loaders/colada-loaders.ts new file mode 100644 index 000000000..8c133f10e --- /dev/null +++ b/playground/src/loaders/colada-loaders.ts @@ -0,0 +1,37 @@ +import { defineColadaLoader } from 'unplugin-vue-router/data-loaders/pinia-colada' +import { ref } from 'vue' + +const delay = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)) +export const simulateError = ref(false) + +export const useUserData = defineColadaLoader('/users/colada-loader.[id]', { + async query(to, { signal }) { + console.log('[๐Ÿน] coladaLoader', to.fullPath) + // signal.addEventListener('abort', () => { + // console.log('[๐ŸนโŒ] aborted', to.fullPath) + // }) + // we need to read these before the delay + const id = to.params.id + // @ts-expect-error: no param "name"! + const name = to.params.name + + await delay(500) + if (simulateError.value) { + throw new Error('Simulated Error') + } + + const user = { + id, + name, + when: new Date().toUTCString(), + } + + return user + }, + key: (to) => { + // console.log('[๐Ÿน] key', to.fullPath) + return ['loader-users', to.params.id] + }, + staleTime: 10000, + // lazy: (to, from) => to.name && to.name === from?.name, +}) diff --git a/playground/src/loaders/todos.ts b/playground/src/loaders/todos.ts new file mode 100644 index 000000000..e69de29bb diff --git a/playground/src/pages/users/colada-loader.[id].vue b/playground/src/pages/users/colada-loader.[id].vue index 4b25ca8c5..8f34a056d 100644 --- a/playground/src/pages/users/colada-loader.[id].vue +++ b/playground/src/pages/users/colada-loader.[id].vue @@ -1,47 +1,5 @@ - -