Skip to content

Conversation

jhonsw1
Copy link

@jhonsw1 jhonsw1 commented Aug 8, 2025

Summary by Sourcery

Enhance WhatsApp Baileys and Business integrations by adding instance management APIs, full-history delivery via webhooks, quoted message and location support, and streamlined media handling. Update caching, logging, and configuration, comment out legacy persistence logic, bump dependencies, and add related Prisma migrations.

New Features:

  • Add getInstanceByName and countInstances endpoints for instance management
  • Introduce downloadMediaMessage API for Baileys channel
  • Allow per-instance override of WhatsApp web version from database
  • Emit full history (contacts and messages) in webhooks via historySetData
  • Support location messages and external ad replies in Business integration
  • Add quoted message parsing and handling in send and update flows

Enhancements:

  • Use Buffer instead of base64 for media and audio payloads
  • Introduce parseQuoted and isMedia helper methods
  • Normalize LID-style JIDs through normalizeLidKey
  • Configure userDevicesCache with 5-minute TTL
  • Standardize logging with logger methods
  • Update Docker base images to Alpine 3.20, bump package to 2.2.40, update Baileys dependency fork

Chores:

  • Comment out legacy database persistence for contacts, chats, messages, and media
  • Add WEBHOOK_TEST env var and adjust meta webhook validation
  • Remove telemetry middleware
  • Add Prisma migrations for webVersion column, IsOnWhatsapp index, and token type change

jhonsw1 and others added 30 commits November 1, 2024 14:59
Lucas Nogueira Mesquita and others added 27 commits May 14, 2025 19:40
Corrige parse de quoted e adiciona retorno de ID após upload de mídia
logs para identificar o valor de contacts que está vindo da baileys
fix: substitui contatos com remoteJid @lid por senderPn
Alteração na coluna token para o tipo text na tabela instances
…ion' agora serão enviados o mediaType como ciphertext
Copy link

sourcery-ai bot commented Aug 8, 2025

Reviewer's Guide

This PR refactors the Baileys WhatsApp integration to support dynamic webVersion loading, buffer-based media handling, quoted messages parsing, and streamlined webhook history payloads; extends the Business service with location and sticker support; adds new API endpoints for instance management and media downloads; upgrades infrastructure (Docker base image, dependencies, Prisma schema); and deprecates many direct DB write paths in favor of webhook events and logs.

Sequence diagram for downloadMediaMessage API flow

sequenceDiagram
    participant Client
    participant BaileysRouter
    participant BaileysController
    participant BaileysStartupService
    Client->>BaileysRouter: POST /downloadMediaMessage
    BaileysRouter->>BaileysController: downloadMediaMessage(instance, body)
    BaileysController->>BaileysStartupService: baileysDownloadMediaMessage(body)
    BaileysStartupService-->>BaileysController: base64 media
    BaileysController-->>BaileysRouter: base64 media
    BaileysRouter-->>Client: base64 media
Loading

Sequence diagram for new instanceByName and countInstances endpoints

sequenceDiagram
    participant Client
    participant InstanceRouter
    participant InstanceController
    participant PrismaRepository
    Client->>InstanceRouter: GET /instance/instanceByName
    InstanceRouter->>InstanceController: getInstanceByName(instance)
    InstanceController->>PrismaRepository: findFirst({ name: instanceName })
    PrismaRepository-->>InstanceController: instance data
    InstanceController-->>InstanceRouter: response
    InstanceRouter-->>Client: response

    Client->>InstanceRouter: GET /instance/countInstances
    InstanceRouter->>InstanceController: countInstances()
    InstanceController->>PrismaRepository: count()
    PrismaRepository-->>InstanceController: count
    InstanceController-->>InstanceRouter: count
    InstanceRouter-->>Client: count
Loading

Class diagram for updated BaileysStartupService and related types

classDiagram
    class BaileysStartupService {
        +parseQuoted(quoted: Quoted)
        +isMedia(message: proto.IMessage): boolean
        +baileysDownloadMediaMessage(message: proto.IWebMessageInfo): Promise<string>
        +normalizeLidKey(key: proto.IMessageKey): string | undefined
        -userDevicesCache: CacheStore
        -msgRetryCounterCache: CacheStore
        -prepareMessage(message: proto.IWebMessageInfo): any
    }
    class IMessageKeyWithExtras {
        senderPn: string | null
        senderLid: string | null
    }
    class wa {
        <<namespace>>
        HistorySetData
        HistorySetContact
    }
    BaileysStartupService ..> IMessageKeyWithExtras : uses
    BaileysStartupService ..> wa : uses

    class wa~HistorySetData~ {
        contacts: HistorySetContact[]
        messages: any[]
    }
    class wa~HistorySetContact~ {
        id: string
        name: string
    }
Loading

Class diagram for BusinessStartupService message handling changes

classDiagram
    class BusinessStartupService {
        -messageLocationJson(received: any)
        -messageTextJson(received: any)
        +isMediaMessage(message: any)
        +prepareMediaMessage(mediaMessage: MediaMessage)
        +mediaMessage(data: SendMediaDto, file?: any)
        +audioWhatsapp(data: SendAudioDto, file?: any)
    }
    BusinessStartupService ..> SendMediaDto
    BusinessStartupService ..> SendAudioDto
Loading

File-Level Changes

Change Details Files
Dynamic webVersion retrieval and socket configuration in Baileys service
  • Fetch webVersion from database and split into numeric array
  • Log and apply webVersion in socketConfig.version
  • Replace static version log message
  • Switch shouldIgnoreJid to use isJidStatusBroadcast
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Media handling overhaul in Baileys integration
  • Switch from base64 strings to Buffer for media and audio payloads
  • Refactor prepareMediaMessage to accept Buffer directly
  • Add isMedia helper to detect media messages
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
Quoted message support and parsing helpers
  • Introduce parseQuoted method and apply it in media/audio send methods
  • Include quoted context in sendDataWebhook calls and controller endpoints
  • Uncomment and adjust handling of quoted fields in Business service
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
src/api/integrations/channel/meta/whatsapp.business.service.ts
src/api/integrations/channel/whatsapp/baileys.controller.ts
Streamlined history sync and event-driven persistence
  • Extend sendDataWebhook signature to accept historySetData
  • Comment out bulk DB writes for contacts, chats, and messages in favor of webhook events
  • Log initial sync data and send historySet payload
src/api/services/channel.service.ts
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
src/api/integrations/event/event.manager.ts
src/api/integrations/event/webhook/webhook.controller.ts
New API endpoints and updated guards
  • Add countInstances and instanceByName routes and controller methods
  • Add downloadMediaMessage endpoint in Baileys router and controller
  • Update authGuard and instanceExistsGuard to whitelist new routes
src/api/controllers/instance.controller.ts
src/api/routes/instance.router.ts
src/api/integrations/channel/whatsapp/baileys.router.ts
src/api/guards/auth.guard.ts
src/api/guards/instance.guard.ts
Business service enhancements for stickers, location, and context
  • Extend isMediaMessage to detect stickers
  • Build JSON for location messages and externalAdReply in text messages
  • Refactor multipart upload to send Buffer with fileName and contentType
src/api/integrations/channel/meta/whatsapp.business.service.ts
Infrastructure and dependency upgrades
  • Upgrade Docker base image to node:20-alpine3.20
  • Bump package.json version and update Baileys dependency commit
  • Add Prisma migrations for webVersion column and index on IsOnWhatsapp
Dockerfile
package.json
prisma/postgresql-migrations/20241105170512_web_version/migration.sql
prisma/postgresql-migrations/20250128200807_added_index_remotejid_on_is_on_whatsapp_table/migration.sql
prisma/postgresql-migrations/20250711181706_change_token_to_text/migration.sql
Utility tweaks and minor fixes
  • Adjust createJid logic threshold from 24 to 23 characters
  • Add IMessageKeyWithExtras interface and normalizeLidKey to handle @lid JIDs
  • Remove redundant telemetry middleware from index.router
src/utils/createJid.ts
src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts
src/api/routes/index.router.ts

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey @jhonsw1 - I've reviewed your changes - here's some feedback:

  • There’s a lot of commented-out legacy code throughout this PR—please remove dead code or extract it behind feature flags to keep the codebase clean and maintainable.
  • The diff uses both console.log and various logger methods for debugging—standardize on your application logger with appropriate levels and remove ad-hoc debug prints.
  • This class is extremely large and mixes message handling, event routing, media processing, and caching—consider refactoring into smaller services or modules to improve readability and testability.
Prompt for AI Agents
Please address the comments from this code review:
## Overall Comments
- There’s a lot of commented-out legacy code throughout this PR—please remove dead code or extract it behind feature flags to keep the codebase clean and maintainable.
- The diff uses both console.log and various logger methods for debugging—standardize on your application logger with appropriate levels and remove ad-hoc debug prints.
- This class is extremely large and mixes message handling, event routing, media processing, and caching—consider refactoring into smaller services or modules to improve readability and testability.

## Individual Comments

### Comment 1
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:899` </location>
<code_context>
-          }
+          this.logger.info("VALOR DA MENSAGEM: " + JSON.stringify(received))
+
+          received.key.remoteJid = this.normalizeLidKey(received?.key);

           if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) {
</code_context>

<issue_to_address>
Overwriting remoteJid may have unintended side effects.

Consider cloning received.key or assigning the normalized value to a new variable to prevent unintended side effects from modifying remoteJid directly.

Suggested implementation:

```typescript
          this.logger.info("VALOR DA MENSAGEM: " + JSON.stringify(received))

          // Clone received.key to avoid mutating the original object
          const normalizedKey = { ...received.key, remoteJid: this.normalizeLidKey(received?.key) };

          if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) {
            const editedMessage =
            }
          }

          let groupInfo;
          const { remoteJid } = normalizedKey;
          if (isJidGroup(remoteJid)) {
            const groupMetaData = await this.getGroupMetadataCache(remoteJid);
            groupInfo = {

```

If there are other usages of `received.key.remoteJid` later in the function, you should update them to use `normalizedKey.remoteJid` instead to ensure consistency and avoid side effects.
</issue_to_address>

### Comment 2
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:2230` </location>
<code_context>
       const prepareMedia = await prepareWAMessageMedia(
         {
-          [type]: isURL(mediaMessage.media) ? { url: mediaMessage.media } : Buffer.from(mediaMessage.media, 'base64'),
+          [type]: isURL(mediaMessage.media) ? { url: mediaMessage.media } : mediaMessage.media,
         } as any,
         { upload: this.client.waUploadToServer },
</code_context>

<issue_to_address>
Directly passing mediaMessage.media may cause issues if not a Buffer.

Validate that mediaMessage.media is either a Buffer or a valid URL before passing it to prepareWAMessageMedia to prevent runtime errors.
</issue_to_address>

### Comment 3
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:2376` </location>
<code_context>

   public async mediaMessage(data: SendMediaDto, file?: any) {
     const mediaData: SendMediaDto = { ...data };
+    data.quoted = this.parseQuoted(data.quoted);

-    if (file) mediaData.media = file.buffer.toString('base64');
</code_context>

<issue_to_address>
Mutating input data object may cause side effects.

Assign the result of parseQuoted to a new variable instead of mutating data directly to avoid unintended side effects.

Suggested implementation:

```typescript
  public async mediaMessage(data: SendMediaDto, file?: any) {
    const quotedMessage = this.parseQuoted(data.quoted);
    const mediaData: SendMediaDto = { ...data, quoted: quotedMessage };

    if (file) mediaData.media = file.buffer;

```

```typescript
  public async audioWhatsapp(data: SendAudioDto, file?: any) {
    const quotedMessage = this.parseQuoted(data.quoted);
    const mediaData: SendAudioDto = { ...data, quoted: quotedMessage };

    if (file?.buffer) {

```
</issue_to_address>

### Comment 4
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:2432` </location>
<code_context>

     if (file?.buffer) {
-      mediaData.audio = file.buffer.toString('base64');
+      // mediaData.audio: Buffer = file.buffer;
     } else if (!isURL(data.audio) && !isBase64(data.audio)) {
       console.error('Invalid file or audio source');
</code_context>

<issue_to_address>
Commented-out code for audio assignment may cause confusion.

Please remove the commented-out assignment or clarify its purpose to avoid confusion during maintenance.
</issue_to_address>

### Comment 5
<location> `src/api/integrations/channel/whatsapp/whatsapp.baileys.service.ts:2442` </location>
<code_context>
     return await this.sendMessageWithTyping<AnyMessageContent>(
       data.number,
       {
-        audio: isURL(data.audio) ? { url: data.audio } : Buffer.from(data.audio, 'base64'),
+        audio: isURL(data.audio) ? { url: data.audio } : file?.buffer,
         ptt: true,
         mimetype: 'audio/ogg; codecs=opus',
       },
-      { presence: 'recording', delay: data?.delay },
+      { presence: 'recording', delay: data?.delay, quoted: data?.quoted },
     );
   }
</code_context>

<issue_to_address>
Passing quoted in options may break if not handled by sendMessageWithTyping.

Verify that sendMessageWithTyping and related logic correctly process the quoted field, including cases where it is an object.

Suggested implementation:

```typescript
  public async audioWhatsapp(data: SendAudioDto, file?: any) {
    const mediaData: SendAudioDto = { ...data };
    data.quoted = this.parseQuoted(data.quoted);

    // Ensure quoted is in the correct format for Baileys
    let quotedMessage = undefined;
    if (data?.quoted) {
      // If quoted is an object, validate/transform as needed
      if (typeof data.quoted === 'object' && data.quoted.messageId && data.quoted.remoteJid) {
        quotedMessage = {
          key: {
            id: data.quoted.messageId,
            remoteJid: data.quoted.remoteJid,
            fromMe: data.quoted.fromMe ?? false,
          },
          message: data.quoted.message,
        };
      } else {
        quotedMessage = data.quoted;
      }
    }

    if (file?.buffer) {
      // mediaData.audio: Buffer = file.buffer;
    } else if (!isURL(data.audio) && !isBase64(data.audio)) {
      console.error('Invalid file or audio source');
      throw new BadRequestException('File buffer, URL, or base64 audio is required');

```

```typescript
     return await this.sendMessageWithTyping<AnyMessageContent>(
       data.number,
       {
         audio: isURL(data.audio) ? { url: data.audio } : file?.buffer,
         ptt: true,
         mimetype: 'audio/ogg; codecs=opus',
       },
       { presence: 'recording', delay: data?.delay, quoted: quotedMessage },
     );
   }

```

You must also verify the implementation of `sendMessageWithTyping`:
- Ensure it passes the `quoted` field to the underlying Baileys `sendMessage` call.
- If not, update `sendMessageWithTyping` to do so, and ensure it expects `quoted` in the correct format (usually as a message object).
- If `parseQuoted` does not guarantee the correct format, consider moving the transformation logic there instead.
</issue_to_address>

### Comment 6
<location> `src/api/integrations/channel/meta/whatsapp.business.service.ts:197` </location>
<code_context>
+        name: message.location.name,
+      },
+    };
+    message.context ? (content = { ...content, contextInfo: { stanzaId: message.context.id } }) : content;
+    return content;
+  }
</code_context>

<issue_to_address>
Assignment in ternary has no effect if condition is false.

Using an if statement would make the assignment clearer and avoid confusion when message.context is falsy.
</issue_to_address>

Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

}
this.logger.info("VALOR DA MENSAGEM: " + JSON.stringify(received))

received.key.remoteJid = this.normalizeLidKey(received?.key);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Overwriting remoteJid may have unintended side effects.

Consider cloning received.key or assigning the normalized value to a new variable to prevent unintended side effects from modifying remoteJid directly.

Suggested implementation:

          this.logger.info("VALOR DA MENSAGEM: " + JSON.stringify(received))

          // Clone received.key to avoid mutating the original object
          const normalizedKey = { ...received.key, remoteJid: this.normalizeLidKey(received?.key) };

          if (received.message?.protocolMessage?.editedMessage || received.message?.editedMessage?.message) {
            const editedMessage =
            }
          }

          let groupInfo;
          const { remoteJid } = normalizedKey;
          if (isJidGroup(remoteJid)) {
            const groupMetaData = await this.getGroupMetadataCache(remoteJid);
            groupInfo = {

If there are other usages of received.key.remoteJid later in the function, you should update them to use normalizedKey.remoteJid instead to ensure consistency and avoid side effects.

@@ -2189,7 +2227,7 @@ export class BaileysStartupService extends ChannelStartupService {

const prepareMedia = await prepareWAMessageMedia(
{
[type]: isURL(mediaMessage.media) ? { url: mediaMessage.media } : Buffer.from(mediaMessage.media, 'base64'),
[type]: isURL(mediaMessage.media) ? { url: mediaMessage.media } : mediaMessage.media,
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

issue (bug_risk): Directly passing mediaMessage.media may cause issues if not a Buffer.

Validate that mediaMessage.media is either a Buffer or a valid URL before passing it to prepareWAMessageMedia to prevent runtime errors.

@@ -2335,8 +2373,9 @@ export class BaileysStartupService extends ChannelStartupService {

public async mediaMessage(data: SendMediaDto, file?: any) {
const mediaData: SendMediaDto = { ...data };
data.quoted = this.parseQuoted(data.quoted);
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (bug_risk): Mutating input data object may cause side effects.

Assign the result of parseQuoted to a new variable instead of mutating data directly to avoid unintended side effects.

Suggested implementation:

  public async mediaMessage(data: SendMediaDto, file?: any) {
    const quotedMessage = this.parseQuoted(data.quoted);
    const mediaData: SendMediaDto = { ...data, quoted: quotedMessage };

    if (file) mediaData.media = file.buffer;
  public async audioWhatsapp(data: SendAudioDto, file?: any) {
    const quotedMessage = this.parseQuoted(data.quoted);
    const mediaData: SendAudioDto = { ...data, quoted: quotedMessage };

    if (file?.buffer) {


if (file?.buffer) {
mediaData.audio = file.buffer.toString('base64');
// mediaData.audio: Buffer = file.buffer;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nitpick: Commented-out code for audio assignment may cause confusion.

Please remove the commented-out assignment or clarify its purpose to avoid confusion during maintenance.

Comment on lines 2442 to +2449
return await this.sendMessageWithTyping<AnyMessageContent>(
data.number,
{
audio: isURL(data.audio) ? { url: data.audio } : Buffer.from(data.audio, 'base64'),
audio: isURL(data.audio) ? { url: data.audio } : file?.buffer,
ptt: true,
mimetype: 'audio/ogg; codecs=opus',
},
{ presence: 'recording', delay: data?.delay },
{ presence: 'recording', delay: data?.delay, quoted: data?.quoted },
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion: Passing quoted in options may break if not handled by sendMessageWithTyping.

Verify that sendMessageWithTyping and related logic correctly process the quoted field, including cases where it is an object.

Suggested implementation:

  public async audioWhatsapp(data: SendAudioDto, file?: any) {
    const mediaData: SendAudioDto = { ...data };
    data.quoted = this.parseQuoted(data.quoted);

    // Ensure quoted is in the correct format for Baileys
    let quotedMessage = undefined;
    if (data?.quoted) {
      // If quoted is an object, validate/transform as needed
      if (typeof data.quoted === 'object' && data.quoted.messageId && data.quoted.remoteJid) {
        quotedMessage = {
          key: {
            id: data.quoted.messageId,
            remoteJid: data.quoted.remoteJid,
            fromMe: data.quoted.fromMe ?? false,
          },
          message: data.quoted.message,
        };
      } else {
        quotedMessage = data.quoted;
      }
    }

    if (file?.buffer) {
      // mediaData.audio: Buffer = file.buffer;
    } else if (!isURL(data.audio) && !isBase64(data.audio)) {
      console.error('Invalid file or audio source');
      throw new BadRequestException('File buffer, URL, or base64 audio is required');
     return await this.sendMessageWithTyping<AnyMessageContent>(
       data.number,
       {
         audio: isURL(data.audio) ? { url: data.audio } : file?.buffer,
         ptt: true,
         mimetype: 'audio/ogg; codecs=opus',
       },
       { presence: 'recording', delay: data?.delay, quoted: quotedMessage },
     );
   }

You must also verify the implementation of sendMessageWithTyping:

  • Ensure it passes the quoted field to the underlying Baileys sendMessage call.
  • If not, update sendMessageWithTyping to do so, and ensure it expects quoted in the correct format (usually as a message object).
  • If parseQuoted does not guarantee the correct format, consider moving the transformation logic there instead.

Comment on lines +300 to +307
const response = {
id: instanceByName.id,
name: instanceByName.name,
ownerJid: instanceByName.ownerJid,
connectionStatus: instanceByName.connectionStatus,
profileName: instanceByName.profileName,
}
return response;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
const response = {
id: instanceByName.id,
name: instanceByName.name,
ownerJid: instanceByName.ownerJid,
connectionStatus: instanceByName.connectionStatus,
profileName: instanceByName.profileName,
}
return response;
return {
id: instanceByName.id,
name: instanceByName.name,
ownerJid: instanceByName.ownerJid,
connectionStatus: instanceByName.connectionStatus,
profileName: instanceByName.profileName,
};


ExplanationSomething that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.

Comment on lines +311 to +312
const count = await this.prismaRepository.instance.count();
return count;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Inline variable that is immediately returned (inline-immediately-returned-variable)

Suggested change
const count = await this.prismaRepository.instance.count();
return count;
return await this.prismaRepository.instance.count();


ExplanationSomething that we often see in people's code is assigning to a result variable
and then immediately returning it.

Returning the result directly shortens the code and removes an unnecessary
variable, reducing the mental load of reading the function.

Where intermediate variables can be useful is if they then get used as a
parameter or a condition, and the name can act like a comment on what the
variable represents. In the case where you're returning it from a function, the
function name is there to tell you what the result is, so the variable name
is unnecessary.

private messageTextJson(received: any) {
let content: any;
const message = received.messages[0];
const referral = message.referral;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Prefer object destructuring when accessing and using properties. (use-object-destructuring)

Suggested change
const referral = message.referral;
const {referral} = message;


ExplanationObject destructuring can often remove an unnecessary temporary reference, as well as making your code more succinct.

From the Airbnb Javascript Style Guide

Comment on lines +960 to 965
} else if(received.message?.protocolMessage){
if(!received.message?.protocolMessage?.editedMessage){
this.logger.verbose('message rejected');
return;
}
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Merge nested if conditions (merge-nested-ifs)

Suggested change
} else if(received.message?.protocolMessage){
if(!received.message?.protocolMessage?.editedMessage){
this.logger.verbose('message rejected');
return;
}
}
} else if (received.message?.protocolMessage && !received.message?.protocolMessage?.editedMessage) {
this.logger.verbose('message rejected');
return;
}


ExplanationReading deeply nested conditional code is confusing, since you have to keep track of which
conditions relate to which levels. We therefore strive to reduce nesting where
possible, and the situation where two if conditions can be combined using
and is an easy win.

},
);

return buffer.toString('base64');;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

suggestion (code-quality): Remove unreachable code. (remove-unreachable-code)

Suggested change
return buffer.toString('base64');;
return buffer.toString('base64');


ExplanationStatements after a return, break, continue or throw will never be executed.
Leaving them in the code confuses the reader, who may believe that these
statements have some effect. They should therefore be removed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants