Skip to content

Instantly share code, notes, and snippets.

@chaosmonster
Last active September 20, 2024 10:44
Show Gist options
  • Save chaosmonster/2c4c7ca2e16488c28a2c2bd7febb3a0b to your computer and use it in GitHub Desktop.
Save chaosmonster/2c4c7ca2e16488c28a2c2bd7febb3a0b to your computer and use it in GitHub Desktop.
A concept inspired by Tanstack Query and angular.js $resource
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'];
});
}
@chaosmonster
Copy link
Author

I added the query() call in the InjectionToken Factory

@chaosmonster
Copy link
Author

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