Skip to content

Commit

Permalink
feat: support abort and progress
Browse files Browse the repository at this point in the history
  • Loading branch information
haoziqaq committed Jul 6, 2023
1 parent e8f7e69 commit 54ee3c3
Show file tree
Hide file tree
Showing 10 changed files with 126 additions and 46 deletions.
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,10 @@
"@varlet/cli": "^2.11.8",
"rimraf": "^5.0.1",
"typescript": "^5.1.5",
"vue": "^3.3.4"
"vue": "3.3.4"
},
"peerDependencies": {
"vue": "^3.2.0"
},
"repository": {
"type": "git",
Expand Down
3 changes: 2 additions & 1 deletion playground/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,10 @@
"@varlet/axle": "link:..",
"@varlet/touch-emulator": "2.11.8",
"@varlet/ui": "^2.11.8",
"@varlet/use": "^2.12.2",
"koa": "^2.14.2",
"koa-router": "^12.0.0",
"koa-bodyparser": "^4.4.0",
"koa-router": "^12.0.0",
"nodemon": "^2.0.15",
"unplugin-auto-import": "^0.16.2",
"vue": "^3.3.1"
Expand Down
16 changes: 16 additions & 0 deletions playground/pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Binary file added playground/public/logo.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
24 changes: 23 additions & 1 deletion playground/src/App.vue
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,24 @@ import {
useApiDeleteUser,
useApiUpdateUser,
useApiPatchUser,
useApiDownloadFile,
User,
} from './apis'
const id = ref('1')
const deleteId = ref('1')
const [users, apiGetUsers, { loading: isUsersLoading }] = useApiGetUsers<User[]>([], { immediate: true })
const [user, apiGetUser, { loading: isUserLoading }] = useApiGetUser<User>({})
const [user, apiGetUser, { loading: isUserLoading, abort }] = useApiGetUser<User>(
{},
{
onSuccess(response) {
if (response.code === 200) {
Snackbar.success('Getting Success!')
}
},
}
)
const [addedUser, apiAddUser] = useApiAddUser<User>(
{},
{
Expand Down Expand Up @@ -66,6 +76,9 @@ const [deletedUser, apiDeleteUser] = useApiDeleteUser<User>(
},
}
)
const [file, apiDownloadFile, { downloadProgress }] = useApiDownloadFile<Blob | null>(null, {
onTransform: (response) => response,
})
const userRecord = reactive<User>({
id: '',
Expand Down Expand Up @@ -100,6 +113,7 @@ watch(
<var-space align="center">
<var-input type="number" variant="outlined" v-model="id" />
<var-button type="primary" @click="apiGetUser({ params: { id } })">Search</var-button>
<var-button type="warning" @click="abort">Abort</var-button>
</var-space>

<var-cell>name: getUser</var-cell>
Expand All @@ -125,4 +139,12 @@ watch(
</var-space>
<var-button type="danger" @click="handleDelete">Delete</var-button>
</var-space>

<var-divider margin="30px 0" />

<var-space direction="column">
<h3>Download Progress: {{ downloadProgress * 100 }} %</h3>
<h3>File Size: {{ file?.size ?? 0 }}</h3>
<var-button type="primary" @click="() => apiDownloadFile()">Download (PS: Please use slow 3G)</var-button>
</var-space>
</template>
9 changes: 9 additions & 0 deletions playground/src/apis/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,12 @@ export function useApiPatchUser<D>(data: D, options?: Options<D, Response<User>>
...options,
})
}

export function useApiDownloadFile<D>(data: D, options?: Options<D, Blob>) {
return useAxle({
data,
url: 'http://localhost:5173/logo.png',
runner: axle.getBlob,
...options,
})
}
2 changes: 1 addition & 1 deletion playground/src/request/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ const useAxle = createUseAxle({

axle.axios.interceptors.response.use(
(response) => {
if (response.data.code !== 200) {
if (response.data.code !== 200 && response.data.message) {
Snackbar.warning(response.data.message)
}

Expand Down
2 changes: 1 addition & 1 deletion playground/src/server.js
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ router.get('/user/list-user', async (ctx) => {
})

router.get('/user/get-user', async (ctx) => {
await delay(300)
await delay(2000)

const user = users.find((user) => user.id === Number(ctx.request.query.id))

Expand Down
42 changes: 19 additions & 23 deletions pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

69 changes: 51 additions & 18 deletions src/use.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { ref, type Ref, type UnwrapRef } from 'vue'
import { ref, type Ref } from 'vue'
import { type AxleRequestConfig, createFetchHelper, createModifyHelper } from './instance.js'

export interface RunOptions<P> {
Expand All @@ -7,7 +7,7 @@ export interface RunOptions<P> {
config?: AxleRequestConfig
}

export type Run<D, P> = (options?: RunOptions<P>) => Promise<UnwrapRef<D>>
export type Run<D, P> = (options?: RunOptions<P>) => Promise<D>

export interface UseAxleOptions<D = any, R = any, P = Record<string, any>> {
url: string
Expand All @@ -18,17 +18,20 @@ export interface UseAxleOptions<D = any, R = any, P = Record<string, any>> {
immediate?: boolean
onBefore?(): void
onAfter?(): void
onTransform?(response: UnwrapRef<R>, prev: UnwrapRef<D>): UnwrapRef<D>
onSuccess?(response: UnwrapRef<R>): void
onTransform?(response: R, prev: D): D
onSuccess?(response: R): void
onError?(error: Error): void
}

export type UseAxleReturn<D, P> = [
data: Ref<UnwrapRef<D>>,
data: Ref<D>,
run: Run<D, P>,
extra: {
loading: Ref<UnwrapRef<boolean>>
error: Ref<UnwrapRef<Error | undefined>>
uploadProgress: Ref<number>
downloadProgress: Ref<number>
loading: Ref<boolean>
error: Ref<Error | undefined>
abort(): void
}
]

Expand All @@ -38,10 +41,8 @@ export interface CreateUseAxleOptions {

export function createUseAxle(options: CreateUseAxleOptions = {}) {
const { onTransform: defaultOnTransform } = options

const useAxle = <D = any, R = any, P = Record<string, any>>(
options: UseAxleOptions<D, R, P>
): UseAxleReturn<D, P> => {

const useAxle = <D = any, R = any, P = Record<string, any>>(options: UseAxleOptions<D, R, P>) => {
const {
url,
runner,
Expand All @@ -51,28 +52,57 @@ export function createUseAxle(options: CreateUseAxleOptions = {}) {
config: initialConfig,
onBefore = () => {},
onAfter = () => {},
onTransform = (defaultOnTransform as UseAxleOptions<D, R, P>['onTransform']) ?? ((response) => response as unknown as UnwrapRef<D>),
onTransform = (defaultOnTransform as UseAxleOptions<D, R, P>['onTransform']) ??
((response) => response as unknown as D),
onSuccess = () => {},
onError = () => {},
} = options

const initialUrl = url
const data = ref<D>(initialData)
const data = ref<D>(initialData) as Ref<D>
const loading = ref(false)
const error = ref<Error>()
const downloadProgress = ref(0)
const uploadProgress = ref(0)

let controller = new AbortController()

const abort = () => {
controller.abort()
}

const run: Run<D, P> = (options: RunOptions<P> = {}) => {
if (controller.signal.aborted) {
controller = new AbortController()
}

uploadProgress.value = 0
downloadProgress.value = 0

const run: Run<D, P> = (options: RunOptions<P> = {}): Promise<UnwrapRef<D>> => {
const url = options.url ?? initialUrl

onBefore()

loading.value = true

return runner(url, options.params, options.config)
return runner(url, options.params, {
signal: controller.signal,

onUploadProgress(event) {
uploadProgress.value = event.progress ?? 0
},

onDownloadProgress(event) {
downloadProgress.value = event.progress ?? 0
},

...options.config,
})
.then((response) => {
data.value = onTransform(response as UnwrapRef<R>, data.value)
data.value = onTransform(response as R, data.value)
error.value = undefined

onSuccess(response as UnwrapRef<R>)
onSuccess(response as R)

return data.value
})
Expand Down Expand Up @@ -103,8 +133,11 @@ export function createUseAxle(options: CreateUseAxleOptions = {}) {
{
loading,
error,
uploadProgress,
downloadProgress,
abort,
},
]
] as UseAxleReturn<D, P>
}

return useAxle
Expand Down

0 comments on commit 54ee3c3

Please sign in to comment.