Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added findOne function to Lens #100

Merged
merged 1 commit into from
Jan 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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