Last active
September 20, 2024 10:44
-
-
Save chaosmonster/2c4c7ca2e16488c28a2c2bd7febb3a0b to your computer and use it in GitHub Desktop.
A concept inspired by Tanstack Query and angular.js $resource
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface ResourceOptions<T> { | |
query: () => Observable<T> | Promise<T>; | |
} | |
interface Resource<T> { | |
query: () => void; | |
data: Signal<T>; | |
state: Signal<'IDLE' | 'PROCESSING' | 'EMITTING' | 'COMPLETE'>; | |
} | |
function createResource<T>(options: ResourceOptions<T>): Resource<T> { | |
// HERE NEEDS TO BE MORE LOGIC | |
return { | |
query: () => {}, | |
data: new Signal<T>(), // this is not readable, but an example | |
state: new Signal('IDLE'), // this is not readable, but an example | |
}; | |
} | |
const ActivatedRouteResource = new InjectionToken('', () => { | |
const activatedRoute = inject(ActivatedRoute); | |
const resource = createResource({ | |
query: () => { | |
return combineLatest(activatedRoute.data, activatedRoute.params).pipe( | |
map(([data, params]) => { | |
return { | |
data, | |
params, | |
}; | |
}) | |
); | |
}, | |
}); | |
resource.query(); | |
return resource; | |
}); | |
class MyComponent { | |
activatedRouteResource = inject(ActivatedRouteResource); | |
id = computed(() => { | |
return this.activatedRouteResource.data()?.params['id']; | |
}); | |
} |
Note: the Resource
is lazy until query()
is called
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I added the
query()
call in theInjectionToken
Factory