Created
January 11, 2025 15:24
-
-
Save jalallinux/2b6bff4d804eb9bcde59cf7d6e5f7ee2 to your computer and use it in GitHub Desktop.
AdonisJS BaseService
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { LucidModel, ModelAttributes, ModelQueryBuilderContract } from '@adonisjs/lucid/types/model' | |
import { QueryCallback } from '@adonisjs/lucid/types/querybuilder' | |
export abstract class BaseService<M extends LucidModel> { | |
protected abstract model: M | |
query(): ModelQueryBuilderContract<M, InstanceType<M>> { | |
return this.model.query() | |
} | |
async all(): Promise<Array<InstanceType<M>>> { | |
return await this.model.all() | |
} | |
async create(attributes: Partial<ModelAttributes<InstanceType<M>>>): Promise<InstanceType<M>> { | |
return await this.model.create(attributes) | |
} | |
async update( | |
id: number | string, | |
attributes: Partial<ModelAttributes<InstanceType<M>>> | |
): Promise<InstanceType<M>> { | |
const record = await this.findOrFail(id) | |
return await record.merge(attributes).save() | |
} | |
async findOrFail(id: number | string): Promise<InstanceType<M>> { | |
return await this.model.findOrFail(id) | |
} | |
async findByOrFail(key: string, value: number | string): Promise<InstanceType<M>> { | |
return await this.model.findByOrFail(key, value) | |
} | |
async findMany( | |
conditions: QueryCallback<ModelQueryBuilderContract<M, InstanceType<M>>> | |
): Promise<Array<InstanceType<M>>> { | |
return await this.query().where(conditions) | |
} | |
async delete(id: number | string): Promise<boolean> { | |
const record = await this.findOrFail(id) | |
await record.delete() | |
return record.$isDeleted | |
} | |
async paginate(page: number = 1, perPage: number = 15) { | |
return await this.query().paginate(page, perPage) | |
} | |
async exists(id: number | string): Promise<boolean> { | |
return !!(await this.model.find(id)) | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import User from '#models/user' | |
import { BaseService } from './base_service.js' | |
export class UserService extends BaseService<typeof User> { | |
protected model = User | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment