Skip to content

Commit

Permalink
Add isResource type predicate (#2)
Browse files Browse the repository at this point in the history
* Add isResource type predicate

* v0.1.1
  • Loading branch information
silverlyra authored Jun 22, 2024
1 parent ae206eb commit 092cc43
Show file tree
Hide file tree
Showing 3 changed files with 61 additions and 4 deletions.
6 changes: 3 additions & 3 deletions deno.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"name": "@kure/schema",
"version": "0.1.0",
"version": "0.1.1",
"exports": {
".": "./mod.ts"
},
"imports": {
"@kure/spec": "jsr:@kure/spec@^0.1.0"
"@kure/spec": "jsr:@kure/spec@^0.1.2"
}
}
}
57 changes: 57 additions & 0 deletions impl.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,60 @@ export function factory<R extends Resource>(

return build;
}

/**
* Create a [type predicate][] for the given {@link ResourceType resource type}.
*
* [type predicate]: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
*
* @example
* ```ts
* import { Pod, Service } from "jsr:@kure/api/core";
* import { isResource } from "jsr:@kure/schema";
*
* export const isPod = isResource(Pod);
* export const isService = isResource(Service);
* ```
*/
export function isResource<R extends Resource>(
type: ResourceType<R>
): (target: unknown) => target is R;
/**
* [Check][type predicate] if a value is an instance of a
* {@link ResourceType resource type}.
*
* [type predicate]: https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates
*
* @example
* ```ts
* import { Deployment } from "jsr:@kure/api/apps";
* import { isResource, type Resource } from "jsr:@kure/schema";
*
* function updateScale(replicas: number, resources: Resource[]) {
* for (const resource of resources) {
* if (isResource(Deployment, resource)) {
* // TypeScript now knows `resource` is a Deployment
* resource.spec.replicas = replicas;
* }
* }
* }
* ```
*/
export function isResource<R extends Resource>(
type: ResourceType<R>,
target: unknown
): target is R;
export function isResource<R extends Resource>(
type: ResourceType<R>,
target?: unknown
) {
if (arguments.length < 2)
return (target: unknown) => isResource(type, target);

return (
target != null &&
typeof target === "object" &&
(target as Resource).apiVersion === type.apiVersion &&
(target as Resource).kind === type.kind
);
}
2 changes: 1 addition & 1 deletion mod.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
export type { Received, ReceivedObjectMeta } from "./disposition.ts";
export * from "./identity.ts";
export { factory } from "./impl.ts";
export { factory, isResource } from "./impl.ts";
export * from "./meta.ts";
export * from "./resource.ts";

Expand Down

0 comments on commit 092cc43

Please sign in to comment.