Skip to content

Commit

Permalink
Added findOne function to Lens (#100)
Browse files Browse the repository at this point in the history
Resolves #95.
  • Loading branch information
karelklima authored Jan 11, 2024
1 parent a8360ec commit 55ea58c
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 0 deletions.
33 changes: 33 additions & 0 deletions library/lens/lens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -235,6 +235,39 @@ export class Lens<T extends Schema> {
return this.decode(graph);
}

/**
* Find one entity that matches the given search criteria.
*
* The search criteria is a JSON object that may contain properties from the data schema.
*
* @example
* ```typescript
* import { createLens } from "ldkit";
* import { schema } from "ldkit/namespaces";
*
* // Create a schema
* const PersonSchema = {
* "@type": schema.Person,
* name: schema.name,
* } as const;
*
* // Create a resource using the data schema above
* const Persons = createLens(PersonSchema);
*
* // Find one person with name that starts with "Ada"
* const person = await Persons.findOne({
* name: { $strStarts: "Ada" },
* });
* ```
*
* @param options Search criteria and pagination options
* @returns entities that match the given search criteria
*/
async findOne(where?: SchemaSearchInterface<T>) {
const results = await this.find({ where, take: 1 });
return results.length > 0 ? results[0] : null;
}

/**
* Find a single entity that matches the given IRI.
*
Expand Down
7 changes: 7 additions & 0 deletions tests/lens_common.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,6 +129,13 @@ Deno.test("Lens / Common / Get resource by quad condition", async () => {
assertEquals(result[0], Tarantino);
});

Deno.test("Lens / Common / Get one resource", async () => {
const { directors } = init();
const result = await directors.findOne();

assertEquals(result, Kubrick);
});

Deno.test("Lens / Common / Count resources", async () => {
const { directors } = init();
const count = await directors.count();
Expand Down

0 comments on commit 55ea58c

Please sign in to comment.