Skip to content

Commit

Permalink
First() returns null instead of D1_NORESULTS
Browse files Browse the repository at this point in the history
  • Loading branch information
Skye-31 committed Sep 27, 2022
1 parent 1b0ebec commit de7eb7d
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 6 deletions.
5 changes: 5 additions & 0 deletions .changeset/five-lizards-try.md
@@ -0,0 +1,5 @@
---
"d1-orm": patch
---

Chore: Make first() return null on a D1_NORESULTS error, as it's inconsistent with local and remote, and that error is near meaningless.
19 changes: 13 additions & 6 deletions src/model.ts
Expand Up @@ -164,20 +164,27 @@ export class Model<T extends object> {

/**
* @param options The options for the query, see {@link GenerateQueryOptions}
* @returns Returns the first row that matches the where clause.
* @returns Returns the first row that matches the where clause, or null if no rows match.
*/
public async First(
options: Pick<GenerateQueryOptions<T>, "where">
): Promise<T> {
): Promise<T | null> {
const statement = GenerateQuery(
QueryType.SELECT,
this.tableName,
Object.assign(options, { limit: 1 })
);
return this.#D1Orm
.prepare(statement.query)
.bind(...statement.bindings)
.first();
try {
return this.#D1Orm
.prepare(statement.query)
.bind(...statement.bindings)
.first();
} catch (e) {
if ((e as Error).message === "D1_NORESULTS") {
return null;
}
throw e;
}
}

/**
Expand Down

0 comments on commit de7eb7d

Please sign in to comment.