init project evolution api

This commit is contained in:
Davidson Gomes
2023-06-09 07:48:59 -03:00
commit 2a1c426311
90 changed files with 9820 additions and 0 deletions

View File

@@ -0,0 +1,57 @@
import { join } from 'path';
import { Auth, ConfigService } from '../../config/env.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { IAuthModel, AuthRaw } from '../models';
import { readFileSync } from 'fs';
import { AUTH_DIR } from '../../config/path.config';
export class AuthRepository extends Repository {
constructor(
private readonly authModel: IAuthModel,
readonly configService: ConfigService,
) {
super(configService);
this.auth = configService.get<Auth>('AUTHENTICATION');
}
private readonly auth: Auth;
public async create(data: AuthRaw, instance: string): Promise<IInsert> {
try {
if (this.dbSettings.ENABLED) {
const insert = await this.authModel.replaceOne(
{ _id: instance },
{ ...data },
{ upsert: true },
);
return { insertCount: insert.modifiedCount };
}
this.writeStore<AuthRaw>({
path: join(AUTH_DIR, this.auth.TYPE),
fileName: instance,
data,
});
return { insertCount: 1 };
} catch (error) {
return { error } as any;
}
}
public async find(instance: string): Promise<AuthRaw> {
try {
if (this.dbSettings.ENABLED) {
return await this.authModel.findOne({ _id: instance });
}
return JSON.parse(
readFileSync(join(AUTH_DIR, this.auth.TYPE, instance + '.json'), {
encoding: 'utf-8',
}),
) as AuthRaw;
} catch (error) {
return {};
}
}
}

View File

@@ -0,0 +1,89 @@
import { join } from 'path';
import { ConfigService } from '../../config/env.config';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { opendirSync, readFileSync, rmSync } from 'fs';
import { ChatRaw, IChatModel } from '../models';
export class ChatQuery {
where: ChatRaw;
}
export class ChatRepository extends Repository {
constructor(
private readonly chatModel: IChatModel,
private readonly configService: ConfigService,
) {
super(configService);
}
public async insert(data: ChatRaw[], saveDb = false): Promise<IInsert> {
if (data.length === 0) {
return;
}
try {
if (this.dbSettings.ENABLED && saveDb) {
const insert = await this.chatModel.insertMany([...data]);
return { insertCount: insert.length };
}
data.forEach((chat) => {
this.writeStore<ChatRaw>({
path: join(this.storePath, 'chats', chat.owner),
fileName: chat.id,
data: chat,
});
});
return { insertCount: data.length };
} catch (error) {
return error;
} finally {
data = undefined;
}
}
public async find(query: ChatQuery): Promise<ChatRaw[]> {
try {
if (this.dbSettings.ENABLED) {
return await this.chatModel.find({ owner: query.where.owner });
}
const chats: ChatRaw[] = [];
const openDir = opendirSync(join(this.storePath, 'chats', query.where.owner));
for await (const dirent of openDir) {
if (dirent.isFile()) {
chats.push(
JSON.parse(
readFileSync(
join(this.storePath, 'chats', query.where.owner, dirent.name),
{ encoding: 'utf-8' },
),
),
);
}
}
return chats;
} catch (error) {
return [];
}
}
public async delete(query: ChatQuery) {
try {
if (this.dbSettings.ENABLED) {
return await this.chatModel.deleteOne({ ...query.where });
}
rmSync(join(this.storePath, 'chats', query.where.owner, query.where.id + '.josn'), {
force: true,
recursive: true,
});
return { deleted: { chatId: query.where.id } };
} catch (error) {
return { error: error?.toString() };
}
}
}

View File

@@ -0,0 +1,88 @@
import { opendirSync, readFileSync } from 'fs';
import { join } from 'path';
import { ConfigService } from '../../config/env.config';
import { ContactRaw, IContactModel } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository';
export class ContactQuery {
where: ContactRaw;
}
export class ContactRepository extends Repository {
constructor(
private readonly contactModel: IContactModel,
private readonly configService: ConfigService,
) {
super(configService);
}
public async insert(data: ContactRaw[], saveDb = false): Promise<IInsert> {
if (data.length === 0) {
return;
}
try {
if (this.dbSettings.ENABLED && saveDb) {
const insert = await this.contactModel.insertMany([...data]);
return { insertCount: insert.length };
}
data.forEach((contact) => {
this.writeStore({
path: join(this.storePath, 'contacts', contact.owner),
fileName: contact.id,
data: contact,
});
});
return { insertCount: data.length };
} catch (error) {
return error;
} finally {
data = undefined;
}
}
public async find(query: ContactQuery): Promise<ContactRaw[]> {
try {
if (this.dbSettings.ENABLED) {
return await this.contactModel.find({ ...query.where });
}
const contacts: ContactRaw[] = [];
if (query?.where?.id) {
contacts.push(
JSON.parse(
readFileSync(
join(
this.storePath,
'contacts',
query.where.owner,
query.where.id + '.json',
),
{ encoding: 'utf-8' },
),
),
);
} else {
const openDir = opendirSync(join(this.storePath, 'contacts', query.where.owner), {
encoding: 'utf-8',
});
for await (const dirent of openDir) {
if (dirent.isFile()) {
contacts.push(
JSON.parse(
readFileSync(
join(this.storePath, 'contacts', query.where.owner, dirent.name),
{ encoding: 'utf-8' },
),
),
);
}
}
}
return contacts;
} catch (error) {
return [];
}
}
}

View File

@@ -0,0 +1,129 @@
import { ConfigService } from '../../config/env.config';
import { join } from 'path';
import { IMessageModel, MessageRaw } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { opendirSync, readFileSync } from 'fs';
export class MessageQuery {
where: MessageRaw;
limit?: number;
}
export class MessageRepository extends Repository {
constructor(
private readonly messageModel: IMessageModel,
private readonly configService: ConfigService,
) {
super(configService);
}
public async insert(data: MessageRaw[], saveDb = false): Promise<IInsert> {
if (!Array.isArray(data) || data.length === 0) {
return;
}
try {
if (this.dbSettings.ENABLED && saveDb) {
const cleanedData = data.map((obj) => {
const cleanedObj = { ...obj };
if ('extendedTextMessage' in obj.message) {
const extendedTextMessage = obj.message.extendedTextMessage as {
contextInfo?: {
mentionedJid?: any;
};
};
if (typeof extendedTextMessage === 'object' && extendedTextMessage !== null) {
if ('contextInfo' in extendedTextMessage) {
delete extendedTextMessage.contextInfo?.mentionedJid;
extendedTextMessage.contextInfo = {};
}
}
}
return cleanedObj;
});
const insert = await this.messageModel.insertMany([...cleanedData]);
return { insertCount: insert.length };
}
if (saveDb) {
data.forEach((msg) =>
this.writeStore<MessageRaw>({
path: join(this.storePath, 'messages', msg.owner),
fileName: msg.key.id,
data: msg,
}),
);
return { insertCount: data.length };
}
return { insertCount: 0 };
} catch (error) {
console.log('ERROR: ', error);
return error;
} finally {
data = undefined;
}
}
public async find(query: MessageQuery) {
try {
if (this.dbSettings.ENABLED) {
if (query?.where?.key) {
for (const [k, v] of Object.entries(query.where.key)) {
query.where['key.' + k] = v;
}
delete query?.where?.key;
}
return await this.messageModel
.find({ ...query.where })
.sort({ messageTimestamp: -1 })
.limit(query?.limit ?? 0);
}
const messages: MessageRaw[] = [];
if (query?.where?.key?.id) {
messages.push(
JSON.parse(
readFileSync(
join(
this.storePath,
'messages',
query.where.owner,
query.where.key.id + '.json',
),
{ encoding: 'utf-8' },
),
),
);
} else {
const openDir = opendirSync(join(this.storePath, 'messages', query.where.owner), {
encoding: 'utf-8',
});
for await (const dirent of openDir) {
if (dirent.isFile()) {
messages.push(
JSON.parse(
readFileSync(
join(this.storePath, 'messages', query.where.owner, dirent.name),
{ encoding: 'utf-8' },
),
),
);
}
}
}
return messages
.sort((x, y) => {
return (y.messageTimestamp as number) - (x.messageTimestamp as number);
})
.splice(0, query?.limit ?? messages.length);
} catch (error) {
return [];
}
}
}

View File

@@ -0,0 +1,96 @@
import { ConfigService } from '../../config/env.config';
import { IMessageUpModel, MessageUpdateRaw } from '../models';
import { IInsert, Repository } from '../abstract/abstract.repository';
import { join } from 'path';
import { opendirSync, readFileSync } from 'fs';
export class MessageUpQuery {
where: MessageUpdateRaw;
limit?: number;
}
export class MessageUpRepository extends Repository {
constructor(
private readonly messageUpModel: IMessageUpModel,
private readonly configService: ConfigService,
) {
super(configService);
}
public async insert(data: MessageUpdateRaw[], saveDb?: boolean): Promise<IInsert> {
if (data.length === 0) {
return;
}
try {
if (this.dbSettings.ENABLED && saveDb) {
const insert = await this.messageUpModel.insertMany([...data]);
return { insertCount: insert.length };
}
data.forEach((update) => {
this.writeStore<MessageUpdateRaw>({
path: join(this.storePath, 'message-up', update.owner),
fileName: update.id,
data: update,
});
});
} catch (error) {
return error;
}
}
public async find(query: MessageUpQuery) {
try {
if (this.dbSettings.ENABLED) {
return await this.messageUpModel
.find({ ...query.where })
.sort({ datetime: -1 })
.limit(query?.limit ?? 0);
}
const messageUpdate: MessageUpdateRaw[] = [];
if (query?.where?.id) {
messageUpdate.push(
JSON.parse(
readFileSync(
join(
this.storePath,
'message-up',
query.where.owner,
query.where.id + '.json',
),
{ encoding: 'utf-8' },
),
),
);
} else {
const openDir = opendirSync(
join(this.storePath, 'message-up', query.where.owner),
{ encoding: 'utf-8' },
);
for await (const dirent of openDir) {
if (dirent.isFile()) {
messageUpdate.push(
JSON.parse(
readFileSync(
join(this.storePath, 'message-up', query.where.owner, dirent.name),
{ encoding: 'utf-8' },
),
),
);
}
}
}
return messageUpdate
.sort((x, y) => {
return y.datetime - x.datetime;
})
.splice(0, query?.limit ?? messageUpdate.length);
} catch (error) {
return [];
}
}
}

View File

@@ -0,0 +1,27 @@
import { MessageRepository } from './message.repository';
import { ChatRepository } from './chat.repository';
import { ContactRepository } from './contact.repository';
import { MessageUpRepository } from './messageUp.repository';
import { MongoClient } from 'mongodb';
import { WebhookRepository } from './webhook.repository';
import { AuthRepository } from './auth.repository';
export class RepositoryBroker {
constructor(
public readonly message: MessageRepository,
public readonly chat: ChatRepository,
public readonly contact: ContactRepository,
public readonly messageUpdate: MessageUpRepository,
public readonly webhook: WebhookRepository,
public readonly auth: AuthRepository,
dbServer?: MongoClient,
) {
this.dbClient = dbServer;
}
private dbClient?: MongoClient;
public get dbServer() {
return this.dbClient;
}
}

View File

@@ -0,0 +1,53 @@
import { IInsert, Repository } from '../abstract/abstract.repository';
import { ConfigService } from '../../config/env.config';
import { join } from 'path';
import { readFileSync } from 'fs';
import { IWebhookModel, WebhookRaw } from '../models';
export class WebhookRepository extends Repository {
constructor(
private readonly webhookModel: IWebhookModel,
private readonly configService: ConfigService,
) {
super(configService);
}
public async create(data: WebhookRaw, instance: string): Promise<IInsert> {
try {
if (this.dbSettings.ENABLED) {
const insert = await this.webhookModel.replaceOne(
{ _id: instance },
{ ...data },
{ upsert: true },
);
return { insertCount: insert.modifiedCount };
}
this.writeStore<WebhookRaw>({
path: join(this.storePath, 'webhook'),
fileName: instance,
data,
});
return { insertCount: 1 };
} catch (error) {
return error;
}
}
public async find(instance: string): Promise<WebhookRaw> {
try {
if (this.dbSettings.ENABLED) {
return await this.webhookModel.findOne({ _id: instance });
}
return JSON.parse(
readFileSync(join(this.storePath, 'webhook', instance + '.json'), {
encoding: 'utf-8',
}),
) as WebhookRaw;
} catch (error) {
return {};
}
}
}