coddyger
Version:
Coddyger est une bibliothèque JavaScript/TypeScript qui fournit des fonctions communes et des plugins pour la gestion des données, la communication entre services, et des utilitaires avancés pour le développement d'applications.
264 lines (237 loc) • 7.85 kB
text/typescript
import { Model, ModelStatic, Op, WhereOptions } from "sequelize";
import { IData, IErrorObject } from "../../interface";
import { defines } from "../../globals";
import { LoggerService, LogLevel } from "../../services";
export class SequelizeDao<T extends Model> implements IData<T> {
defaultModel!: ModelStatic<T>;
private logError(e: any, method: string): IErrorObject {
LoggerService.log({
type: LogLevel.Error,
content: e,
location: "SequelizeDao",
method,
});
return { error: true, data: e, message: defines.message.tryCatch };
}
/* -----------------------------------
| ENREGISTRER UN DOCUMENT
----------------------------------- */
async save(data: any): Promise<any> {
try {
const doc = await this.defaultModel.create(data);
return doc || Promise.reject(doc);
} catch (e: any) {
return this.logError(e, "save");
}
}
async saveMany(data: Array<any>): Promise<any> {
try {
const docs = await this.defaultModel.bulkCreate(data);
if (!docs) throw docs;
return docs;
} catch (e) {
return this.logError(e, "saveMany");
}
}
async update(params: WhereOptions, data: any): Promise<any> {
try {
const [affectedCount] = await this.defaultModel.update(data, {
where: params,
});
return affectedCount > 0
? { affectedCount }
: Promise.reject({ affectedCount });
} catch (e: any) {
return this.logError(e, "update");
}
}
async updateMany(params: WhereOptions, data: any): Promise<any> {
try {
const [affectedCount] = await this.defaultModel.update(data, {
where: params,
});
return { affectedCount };
} catch (e: any) {
return this.logError(e, "updateMany");
}
}
/* -----------------------------------
| SELECTIONNE DES DOCUMENTS
----------------------------------- */
async select(payloads: {
params?: WhereOptions;
excludes?: string[];
page?: number;
pageSize?: number;
sort?: string;
orderBy?: string;
}): Promise<any | IErrorObject> {
try {
let {
page = 1,
pageSize = 10,
sort: sortBy,
orderBy,
params,
excludes,
} = payloads;
page = Math.max(1, page);
const offset = (page - 1) * pageSize;
const order: any = sortBy
? [[sortBy, orderBy === "desc" ? "DESC" : "ASC"]]
: [["createdAt", "DESC"]];
const { rows, count } = await this.defaultModel.findAndCountAll({
where: params,
attributes: { exclude: excludes },
order,
offset,
limit: pageSize,
});
if (!rows) return Promise.reject({ rows, count });
const totalPages = Math.ceil(count / pageSize);
return {
rows,
totalRows: count,
totalPages,
countRowsPerPage: rows.length,
totalPagesPerQuery: totalPages,
};
} catch (e: any) {
return this.logError(JSON.stringify(e), "select");
}
}
async selectOne(params: WhereOptions, fields?: string): Promise<any> {
try {
const doc = await this.defaultModel.findOne({
where: params,
attributes: fields ? fields.split(',') : undefined,
});
return doc || Promise.reject(doc);
} catch (e: any) {
return this.logError(e, "selectOne");
}
}
async selectLatest(status?: string): Promise<any> {
try {
const whereClause: WhereOptions = status ? { status } : {};
const doc = await this.defaultModel.findOne({
where: whereClause,
order: [["createdAt", "DESC"]],
});
return doc || Promise.reject(doc);
} catch (e: any) {
return this.logError(e, "selectLatest");
}
}
async selectLatestWithParams(params: WhereOptions, excludeFields?: string): Promise<any> {
try {
const doc = await this.defaultModel.findOne({ where: params, attributes: excludeFields ? excludeFields.split(',') : undefined });
return doc || Promise.reject(doc);
} catch (e: any) {
return this.logError(e, "selectLatestWithParams");
}
}
async count(params: WhereOptions): Promise<any> {
try {
const count = await this.defaultModel.count({ where: params });
return count || Promise.reject(count);
} catch (e: any) {
return this.logError(e, "count");
}
}
async exist(params: WhereOptions): Promise<any> {
try {
const count = await this.defaultModel.count({ where: params });
return count >= 1;
} catch (e: any) {
return this.logError(e, "exist");
}
}
// Note: Sequelize doesn't have a direct equivalent to MongoDB's aggregate.
// You might need to use raw queries or multiple queries to achieve similar functionality.
async aggregate(params: Array<any>): Promise<any> {
try {
// This is a placeholder. You'll need to implement this based on your specific needs.
throw new Error("Aggregate method not implemented for Sequelize");
} catch (e: any) {
return this.logError(e, "aggregate");
}
}
async selectHug(params?: WhereOptions): Promise<any> {
try {
const docs = await this.defaultModel.findAll({ where: params });
return docs || Promise.reject(docs);
} catch (e: any) {
return this.logError(e, "selectHug");
}
}
/* -----------------------------------
| SUPPRIMER UN DOCUMENT
----------------------------------- */
async remove(params: WhereOptions): Promise<any> {
try {
const affectedCount = await this.defaultModel.destroy({ where: params });
return affectedCount > 0
? { affectedCount }
: Promise.reject({ affectedCount });
} catch (e: any) {
return this.logError(e, "remove");
}
}
async removeMany(params: WhereOptions): Promise<any> {
try {
const affectedCount = await this.defaultModel.destroy({ where: params });
return { affectedCount };
} catch (e: any) {
return this.logError(e, "removeMany");
}
}
async findByPk(id: any, options: any = {}): Promise<any> {
try {
const doc = await this.defaultModel.findByPk(id, options);
return doc || Promise.reject(doc);
} catch (e: any) {
return this.logError(e, "findByPk");
}
}
async findAll(options: any = {}): Promise<any> {
try {
const docs = await this.defaultModel.findAll(options);
return docs || Promise.reject(docs);
} catch (e: any) {
return this.logError(e, "findAll");
}
}
async increment(params: WhereOptions, field: string, by: number = 1): Promise<any> {
try {
const result = await this.defaultModel.increment(field, { by, where: params });
return result;
} catch (e: any) {
return this.logError(e, "increment");
}
}
async decrement(params: WhereOptions, field: string, by: number = 1): Promise<any> {
try {
const result = await this.defaultModel.decrement(field, { by, where: params });
return result;
} catch (e: any) {
return this.logError(e, "decrement");
}
}
async upsert(data: any, options: any = {}): Promise<any> {
try {
const result = await this.defaultModel.upsert(data, options);
return result;
} catch (e: any) {
return this.logError(e, "upsert");
}
}
async restore(params: WhereOptions): Promise<any> {
try {
const result = await this.defaultModel.restore({ where: params });
return result;
} catch (e: any) {
return this.logError(e, "restore");
}
}
}