From 55ea58c941ebe1b4ddb0fe2256efb9077ab40a57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Karel=20Kl=C3=ADma?= Date: Thu, 11 Jan 2024 23:33:28 +0100 Subject: [PATCH] Added `findOne` function to Lens (#100) Resolves #95. --- library/lens/lens.ts | 33 +++++++++++++++++++++++++++++++++ tests/lens_common.test.ts | 7 +++++++ 2 files changed, 40 insertions(+) diff --git a/library/lens/lens.ts b/library/lens/lens.ts index 29304b0..1b2ddfb 100644 --- a/library/lens/lens.ts +++ b/library/lens/lens.ts @@ -235,6 +235,39 @@ export class Lens { 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) { + const results = await this.find({ where, take: 1 }); + return results.length > 0 ? results[0] : null; + } + /** * Find a single entity that matches the given IRI. * diff --git a/tests/lens_common.test.ts b/tests/lens_common.test.ts index 2239485..5eafe20 100644 --- a/tests/lens_common.test.ts +++ b/tests/lens_common.test.ts @@ -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();