Skip to content

Commit

Permalink
fix(prepareData): 仅支持函数形式
Browse files Browse the repository at this point in the history
  • Loading branch information
fjc0k committed May 9, 2023
1 parent 5d2154e commit 4d55bce
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 16 deletions.
15 changes: 6 additions & 9 deletions src/utils/prepareData.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,17 +4,14 @@ import { prepareData } from './prepareData'
describe('prepareData', () => {
test('ok', async () => {
const data = await prepareData({
x: 1,
y: Promise.resolve(Promise.resolve('y')),
z: null,
f: () => 'fn',
fa: async () => 'fns',
})
expectType<typeof data['x'], number>()
expectType<typeof data['y'], string>()
expectType<typeof data['z'], null>()
expectType<typeof data['f'], 'fn'>()
expectType<typeof data['fa'], string>()
expect(data).toEqual({
x: 1,
y: 'y',
z: null,
f: 'fn',
fa: 'fns',
})
})
})
15 changes: 8 additions & 7 deletions src/utils/prepareData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,20 @@ import { isPromiseLike } from './isPromiseLike'
*
* @param getter 数据源
*/
export function prepareData<T extends Record<string, any>>(
export function prepareData<T extends Record<string, () => any>>(
getter: T,
): Promise<
{
[K in keyof T]: Awaited<T[K]>
[K in keyof T]: Awaited<ReturnType<T[K]>>
}
> {
return Promise.all<[string, any]>(
Object.keys(getter).map(key =>
isPromiseLike(getter[key])
? getter[key].then((value: any) => [key, value])
: [key, getter[key]],
),
Object.keys(getter).map(key => {
const v = getter[key]()
return isPromiseLike(v)
? v.then((value: any) => [key, value])
: ([key, v] as any)
}),
).then<any>(list =>
list.reduce<any>((res, item) => {
res[item[0]] = item[1]
Expand Down

0 comments on commit 4d55bce

Please sign in to comment.