Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Formatação de Código #31

Merged
merged 8 commits into from
Jul 26, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 11 additions & 3 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ module.exports = {
parserOptions: {
sourceType: 'CommonJS',
},
plugins: ['@typescript-eslint/eslint-plugin'],
plugins: [
'@typescript-eslint',
'simple-import-sort',
'import'
],
extends: [
'eslint:recommended',
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
'plugin:prettier/recommended'
],
globals: {
Expand All @@ -26,7 +30,11 @@ module.exports = {
'@typescript-eslint/no-explicit-any': 'off',
'@typescript-eslint/no-empty-function': 'off',
'@typescript-eslint/no-non-null-assertion': 'off',
'@typescript-eslint/no-unused-vars': 'off',
'@typescript-eslint/no-unused-vars': 'error',
'import/first': 'error',
'import/no-duplicates': 'error',
'simple-import-sort/imports': 'error',
'simple-import-sort/exports': 'error',
'@typescript-eslint/ban-types': [
'error',
{
Expand Down
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,12 +22,13 @@ docker-compose.yaml
/yarn.lock
/package-lock.json

# IDE - VSCode
# IDEs
.vscode/*
!.vscode/settings.json
!.vscode/tasks.json
!.vscode/launch.json
!.vscode/extensions.json
.nova/*

# Prisma
/prisma/migrations
Expand All @@ -40,3 +41,6 @@ docker-compose.yaml
/store

/temp/*

.DS_Store
*.DS_Store
9 changes: 6 additions & 3 deletions .prettierrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,11 @@ module.exports = {
semi: true,
trailingComma: 'all',
singleQuote: true,
printWidth: 90,
printWidth: 120,
arrowParens: 'always',
tabWidth: 2,
bracketSameLine: true,
bracketSpacing: true
useTabs: false,
bracketSameLine: false,
bracketSpacing: true,
parser: 'typescript'
}
14 changes: 9 additions & 5 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,8 @@
"start": "ts-node --files --transpile-only ./src/main.ts",
"start:prod": "bash start.sh",
"dev:server": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./src/main.ts",
"test": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./test/all.test.ts"
"test": "clear && tsnd --files --transpile-only --respawn --ignore-watch node_modules ./test/all.test.ts",
"lint": "eslint --fix --ext .ts src"
},
"repository": {
"type": "git",
Expand Down Expand Up @@ -80,16 +81,19 @@
"@types/express": "^4.17.17",
"@types/js-yaml": "^4.0.5",
"@types/jsonwebtoken": "^8.5.9",
"@types/mime-types": "^2.1.1",
"@types/node": "^18.15.11",
"@types/qrcode": "^1.5.0",
"@types/qrcode-terminal": "^0.12.0",
"@types/uuid": "^8.3.4",
"@typescript-eslint/eslint-plugin": "^5.57.1",
"@typescript-eslint/parser": "^5.57.1",
"eslint": "^8.38.0",
"@typescript-eslint/eslint-plugin": "^5.62.0",
"@typescript-eslint/parser": "^5.62.0",
"eslint": "^8.45.0",
"eslint-config-prettier": "^8.8.0",
"eslint-plugin-import": "^2.27.5",
"eslint-plugin-prettier": "^4.2.1",
"prettier": "^2.8.7",
"eslint-plugin-simple-import-sort": "^10.0.0",
"prettier": "^2.8.8",
"ts-node-dev": "^2.0.0",
"typescript": "^4.9.5"
}
Expand Down
22 changes: 5 additions & 17 deletions src/config/env.config.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { isBooleanString } from 'class-validator';
import { readFileSync } from 'fs';
import { load } from 'js-yaml';
import { join } from 'path';
import { isBooleanString } from 'class-validator';

export type HttpServer = { TYPE: 'http' | 'https'; PORT: number; URL: string };

Expand All @@ -14,15 +14,7 @@ export type Cors = {

export type LogBaileys = 'fatal' | 'error' | 'warn' | 'info' | 'debug' | 'trace';

export type LogLevel =
| 'ERROR'
| 'WARN'
| 'DEBUG'
| 'INFO'
| 'LOG'
| 'VERBOSE'
| 'DARK'
| 'WEBHOOKS';
export type LogLevel = 'ERROR' | 'WARN' | 'DEBUG' | 'INFO' | 'LOG' | 'VERBOSE' | 'DARK' | 'WEBHOOKS';

export type Log = {
LEVEL: LogLevel[];
Expand Down Expand Up @@ -156,9 +148,7 @@ export class ConfigService {
}

private envYaml(): Env {
return load(
readFileSync(join(process.cwd(), 'src', 'env.yml'), { encoding: 'utf-8' }),
) as Env;
return load(readFileSync(join(process.cwd(), 'src', 'env.yml'), { encoding: 'utf-8' })) as Env;
}

private envProcess(): Env {
Expand Down Expand Up @@ -244,8 +234,7 @@ export class ConfigService {
CONNECTION_UPDATE: process.env?.WEBHOOK_EVENTS_CONNECTION_UPDATE === 'true',
GROUPS_UPSERT: process.env?.WEBHOOK_EVENTS_GROUPS_UPSERT === 'true',
GROUP_UPDATE: process.env?.WEBHOOK_EVENTS_GROUPS_UPDATE === 'true',
GROUP_PARTICIPANTS_UPDATE:
process.env?.WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
GROUP_PARTICIPANTS_UPDATE: process.env?.WEBHOOK_EVENTS_GROUP_PARTICIPANTS_UPDATE === 'true',
CALL: process.env?.WEBHOOK_EVENTS_CALL === 'true',
NEW_JWT_TOKEN: process.env?.WEBHOOK_EVENTS_NEW_JWT_TOKEN === 'true',
},
Expand All @@ -262,8 +251,7 @@ export class ConfigService {
API_KEY: {
KEY: process.env.AUTHENTICATION_API_KEY,
},
EXPOSE_IN_FETCH_INSTANCES:
process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true',
EXPOSE_IN_FETCH_INSTANCES: process.env?.AUTHENTICATION_EXPOSE_IN_FETCH_INSTANCES === 'true',
JWT: {
EXPIRIN_IN: Number.isInteger(process.env?.AUTHENTICATION_JWT_EXPIRIN_IN)
? Number.parseInt(process.env.AUTHENTICATION_JWT_EXPIRIN_IN)
Expand Down
3 changes: 2 additions & 1 deletion src/config/logger.config.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { configService, Log } from './env.config';
import dayjs from 'dayjs';

import { configService, Log } from './env.config';

const formatDateLog = (timestamp: number) =>
dayjs(timestamp)
.toDate()
Expand Down
1 change: 1 addition & 0 deletions src/db/db.connect.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import mongoose from 'mongoose';

import { configService, Database } from '../config/env.config';
import { Logger } from '../config/logger.config';

Expand Down
23 changes: 6 additions & 17 deletions src/db/redis.client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
import { createClient, RedisClientType } from '@redis/client';
import { Logger } from '../config/logger.config';
import { BufferJSON } from '@whiskeysockets/baileys';

import { Redis } from '../config/env.config';
import { Logger } from '../config/logger.config';

export class RedisCache {
constructor() {
Expand Down Expand Up @@ -59,11 +60,7 @@ export class RedisCache {
this.logger.verbose('writeData: ' + field);
const json = JSON.stringify(data, BufferJSON.replacer);

return await this.client.hSet(
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
json,
);
return await this.client.hSet(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field, json);
} catch (error) {
this.logger.error(error);
}
Expand All @@ -72,10 +69,7 @@ export class RedisCache {
public async readData(field: string) {
try {
this.logger.verbose('readData: ' + field);
const data = await this.client.hGet(
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
);
const data = await this.client.hGet(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field);

if (data) {
this.logger.verbose('readData: ' + field + ' success');
Expand All @@ -92,10 +86,7 @@ export class RedisCache {
public async removeData(field: string) {
try {
this.logger.verbose('removeData: ' + field);
return await this.client.hDel(
this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
field,
);
return await this.client.hDel(this.redisEnv.PREFIX_KEY + ':' + this.instanceName, field);
} catch (error) {
this.logger.error(error);
}
Expand All @@ -104,9 +95,7 @@ export class RedisCache {
public async delAll(hash?: string) {
try {
this.logger.verbose('instance delAll: ' + hash);
const result = await this.client.del(
hash || this.redisEnv.PREFIX_KEY + ':' + this.instanceName,
);
const result = await this.client.del(hash || this.redisEnv.PREFIX_KEY + ':' + this.instanceName);

return result;
} catch (error) {
Expand Down
18 changes: 9 additions & 9 deletions src/main.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import 'express-async-errors';

// import * as Sentry from '@sentry/node';
import compression from 'compression';
import { configService, Cors, HttpServer } from './config/env.config';
import cors from 'cors';
import express, { json, NextFunction, Request, Response, urlencoded } from 'express';
import { join } from 'path';

import { configService, Cors, HttpServer } from './config/env.config';
import { onUnexpectedError } from './config/error.config';
import { Logger } from './config/logger.config';
import { ROOT_DIR } from './config/path.config';
import { waMonitor } from './whatsapp/whatsapp.module';
import { HttpStatus, router } from './whatsapp/routers/index.router';
import 'express-async-errors';
import { ServerUP } from './utils/server-up';
import * as Sentry from '@sentry/node';
import { HttpStatus, router } from './whatsapp/routers/index.router';
import { waMonitor } from './whatsapp/whatsapp.module';

function initWA() {
waMonitor.loadInstance();
Expand Down Expand Up @@ -73,7 +75,7 @@ function bootstrap() {
// });

app.use(
(err: Error, req: Request, res: Response, next: NextFunction) => {
(err: Error, req: Request, res: Response) => {
if (err) {
return res.status(err['status'] || 500).json(err);
}
Expand All @@ -96,9 +98,7 @@ function bootstrap() {
ServerUP.app = app;
const server = ServerUP[httpServer.TYPE];

server.listen(httpServer.PORT, () =>
logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT),
);
server.listen(httpServer.PORT, () => logger.log(httpServer.TYPE.toUpperCase() + ' - ON: ' + httpServer.PORT));

initWA();

Expand Down
5 changes: 3 additions & 2 deletions src/utils/server-up.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import { Express } from 'express';
import { readFileSync } from 'fs';
import { configService, SslConf } from '../config/env.config';
import * as https from 'https';
import * as http from 'http';
import * as https from 'https';

import { configService, SslConf } from '../config/env.config';

export class ServerUP {
static #app: Express;
Expand Down
21 changes: 13 additions & 8 deletions src/utils/use-multi-file-auth-state-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
proto,
SignalDataTypeMap,
} from '@whiskeysockets/baileys';

import { configService, Database } from '../config/env.config';
import { Logger } from '../config/logger.config';
import { dbserver } from '../db/db.connect';
Expand All @@ -24,12 +25,12 @@ export async function useMultiFileAuthStateDb(
const writeData = async (data: any, key: string): Promise<any> => {
try {
await client.connect();
return await collection.replaceOne(
{ _id: key },
JSON.parse(JSON.stringify(data, BufferJSON.replacer)),
{ upsert: true },
);
} catch {}
return await collection.replaceOne({ _id: key }, JSON.parse(JSON.stringify(data, BufferJSON.replacer)), {
upsert: true,
});
} catch (error) {
logger.error(error);
}
};

const readData = async (key: string): Promise<any> => {
Expand All @@ -38,14 +39,18 @@ export async function useMultiFileAuthStateDb(
const data = await collection.findOne({ _id: key });
const creds = JSON.stringify(data);
return JSON.parse(creds, BufferJSON.reviver);
} catch {}
} catch (error) {
logger.error(error);
}
};

const removeData = async (key: string) => {
try {
await client.connect();
return await collection.deleteOne({ _id: key });
} catch {}
} catch (error) {
logger.error(error);
}
};

const creds: AuthenticationCreds = (await readData('creds')) || initAuthCreds();
Expand Down
4 changes: 2 additions & 2 deletions src/utils/use-multi-file-auth-state-redis-db.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,9 @@ import {
proto,
SignalDataTypeMap,
} from '@whiskeysockets/baileys';
import { RedisCache } from '../db/redis.client';

import { Logger } from '../config/logger.config';
import { Redis } from '../config/env.config';
import { RedisCache } from '../db/redis.client';

export async function useMultiFileAuthStateRedisDb(cache: RedisCache): Promise<{
state: AuthenticationState;
Expand Down
35 changes: 4 additions & 31 deletions src/validate/validate.schema.ts
Original file line number Diff line number Diff line change
Expand Up @@ -877,23 +877,8 @@ export const chatwootSchema: JSONSchema7 = {
reopen_conversation: { type: 'boolean', enum: [true, false] },
conversation_pending: { type: 'boolean', enum: [true, false] },
},
required: [
'enabled',
'account_id',
'token',
'url',
'sign_msg',
'reopen_conversation',
'conversation_pending',
],
...isNotEmpty(
'account_id',
'token',
'url',
'sign_msg',
'reopen_conversation',
'conversation_pending',
),
required: ['enabled', 'account_id', 'token', 'url', 'sign_msg', 'reopen_conversation', 'conversation_pending'],
...isNotEmpty('account_id', 'token', 'url', 'sign_msg', 'reopen_conversation', 'conversation_pending'),
};

export const settingsSchema: JSONSchema7 = {
Expand All @@ -907,18 +892,6 @@ export const settingsSchema: JSONSchema7 = {
read_messages: { type: 'boolean', enum: [true, false] },
read_status: { type: 'boolean', enum: [true, false] },
},
required: [
'reject_call',
'groups_ignore',
'always_online',
'read_messages',
'read_status',
],
...isNotEmpty(
'reject_call',
'groups_ignore',
'always_online',
'read_messages',
'read_status',
),
required: ['reject_call', 'groups_ignore', 'always_online', 'read_messages', 'read_status'],
...isNotEmpty('reject_call', 'groups_ignore', 'always_online', 'read_messages', 'read_status'),
};
Loading