Skip to content

Commit 04cf727

Browse files
committed
feat(model): add findOrCreate method
1 parent 36abf73 commit 04cf727

5 files changed

Lines changed: 46 additions & 3 deletions

File tree

package-lock.json

Lines changed: 2 additions & 2 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

package.json

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "@athenna/database",
3-
"version": "5.37.0",
3+
"version": "5.38.0",
44
"description": "The Athenna database handler for SQL/NoSQL.",
55
"license": "MIT",
66
"author": "João Lenon <lenon@athenna.io>",

src/database/drivers/Driver.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -374,6 +374,19 @@ export abstract class Driver<Client = any, QB = any> {
374374
return data
375375
}
376376

377+
/**
378+
* Find a value in database or create a new one if it doesn't exist.
379+
*/
380+
public async findOrCreate<T = any>(data: Partial<T>): Promise<T> {
381+
const hasValue = await this.find()
382+
383+
if (hasValue) {
384+
return hasValue
385+
}
386+
387+
return this.create(data)
388+
}
389+
377390
/**
378391
* Return a single model instance or, if no results are found,
379392
* execute the given closure.

src/models/BaseModel.ts

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -287,6 +287,23 @@ export class BaseModel {
287287
return query.findOrFail()
288288
}
289289

290+
/**
291+
* Find a value in database or create a new one if it doesn't exist.
292+
*/
293+
public static async findOrCreate<T extends typeof BaseModel>(
294+
this: T,
295+
where: Partial<InstanceType<T>>,
296+
data: Partial<InstanceType<T>>
297+
): Promise<InstanceType<T>> {
298+
const query = this.query()
299+
300+
if (where) {
301+
query.where(where)
302+
}
303+
304+
return query.findOrCreate(data)
305+
}
306+
290307
/**
291308
* Return a single data or, if no results are found,
292309
* execute the given closure.

src/models/builders/ModelQueryBuilder.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -258,6 +258,19 @@ export class ModelQueryBuilder<
258258
return data
259259
}
260260

261+
/**
262+
* Find a value in database or create a new one if it doesn't exist.
263+
*/
264+
public async findOrCreate(data: Partial<M> = {}) {
265+
const hasValue = await this.find()
266+
267+
if (hasValue) {
268+
return hasValue
269+
}
270+
271+
return this.create(data)
272+
}
273+
261274
/**
262275
* Return a single data or, if no results are found,
263276
* execute the given closure.

0 commit comments

Comments
 (0)