Connection
The main.ts
includes an async function, which will connect our application:
1import { WAFactory } from '@fastwa/core';
2
3async function connectToWhatsapp() {
4 const app = await WAFactory.create(AppModule. {
5 printQrInTerminal: true
6 });
7
8 await app.listen();
9}
10
11connectToWhatsapp();
Hint: Caching makes the store faster to send/receive messages. e.g. You can use node-cache package to store retry counts of messages when decryption/encryption fails.
Saving and Restoring Sessions
You obviously don't want to keep scanning the QR code every time you want to connect. So, you can load the credentials to log back in.
1import {
2 fetchLatestBaileysVersion,
3 useMultiFileAuthState
4} from '@whiskeysockets/baileys';
5
6async function connectToWhatsapp() {
7 const { state, saveCreds } = await useMultiFileAuthState('./sessions');
8
9 const app = await WAFactory.create(AppModule, {
10 auth: state,
11 printQRInTerminal: true,
12 saveCreds
13 });
14
15 await app.listen();
16}
17
18connectToWhatsapp()
This function useMultiFileAuthState()
save the auth state in a single folder.
Saving Auth keys in Database
Saving keys in a database offers advantages in terms of organization, performance, security, scalability, and data integrity, making it a preferred choice for many developers and applications.
For example, this function provides session management for storing auth state in a database. It is designed to be used with baileys and offers functions to interact with the database for retrieving and storing session data.
1import { initAuthCreds } from "@whiskeysockets/baileys"
2
3export async function useDatabaseAuthState() {
4 const creds = initAuthCreds();
5
6 const state = {
7 creds,
8 keys: {
9 async get<T extends keyof SignalDataTypeMap>(types: T, ids: string[]) {
10 // Get session from database
11 return credsRepository.findOne();
12 },
13 async set(data: SignalDataSet) {
14 // Update or insert session in database
15 credsRepository.upsert();
16 }
17 }
18 }
19
20 const saveCreds = () => credsRepository.save(creds)
21
22 return {
23 state,
24 saveCreds
25 }
26}
Good to know:
useDatabaseAuthState()
works similarly touseMultiFileAuthState()
, but instead of saving it in a JSON file, saves it in the database.
Note: The
useDatabaseAuthState()
function assumes the presence of a repository or database access layer that provides the necessary methods to interact with the database. You need to implement the specific database operations within theget
andset
functions, such as querying the database or using an ORM.