npm package: @geeklabs-co/leco-notification-db
Description: ## Overview
Latest version: 0.1.0

# NotificationDB Package

## Overview

The `NotificationDB` package provides a structured and efficient way to manage notifications in a database, specifically supporting both SMS and Email notifications. It includes functionalities for inserting, retrieving, updating, and searching notifications with validation using `zod` schemas. Additionally, it integrates with TypeSense for fuzzy search capabilities.

## Features

- Supports both **SMS** and **Email** notifications.
- Uses `zod` for schema validation and type safety.
- Provides methods for inserting, updating, and deleting notifications.
- Supports batch operations for efficiency.
- Includes TypeSense integration for searching notifications.
- DynamoDB as the primary data store.
- Strongly typed interfaces for better developer experience.

## Setup environment variables

```shell
AWS_REGION=us-west-2

TYPESENSE_HOST=localhost
TYPESENSE_PORT=8108
TYPESENSE_PROTOCOL=http
TYPESENSE_API_KEY=1234

SMS_TABLE_NAME="dev-sms"
EMAIL_TABLE_NAME="dev-email"

TYPESENSE_CONNECTION_TIMEOUT=120
```

this are the environment variables needed for the packages.

You can use a `.env` file in project folder to load them.

## Installation

To install the package, use npm or yarn:

```sh
npm install notification-db
```

or

```sh
yarn add notification-db
```

## Usage

### Importing the package

```typescript
import {
  lecoNqDB,
  NOTIFICATION,
  INSERT_NOTIFICATION_TYPE,
} from "@geeklabs-co/leco-notification-db";
```

### Importing the package (NextJS) with example

```typescript
"use client";

import { nextLecoNqDBBuilder } from "@geeklabs-co/leco-notification-db";
import { useEffect, useState } from "react";

const lecoNqDB = nextLecoNqDBBuilder({
  emailTableName: "NEXT_PUBLIC_EMAIL_TABLE_NAME",
  smsTableName: "NEXT_PUBLIC_SMS_TABLE_NAME",
  typsenseConfig: {
    nodes: [
      {
        host: process.env.NEXT_PUBLIC_TYPESENSE_HOST || "localhost",
        port: parseInt(process.env.NEXT_PUBLIC_TYPESENSE_PORT || "8108"),
        protocol: process.env.NEXT_PUBLIC_TYPESENSE_PROTOCOL || "http",
      },
    ],
    apiKey: process.env.NEXT_PUBLIC_TYPESENSE_API_KEY || "api-key",
    connectionTimeoutSeconds:
      Number(process.env.NEXT_PUBLIC_TYPESENSE_CONNECTION_TIMEOUT) || 2 * 60,
  },
});

export default function Home() {
  const [data, setData] = useState<object>({});
  useEffect(() => {
    const getEmails = async (email: string) => {
      const data = await lecoNqDB.searchEmailByAddress({
        email,
      });
      console.dir(data);
      setData(data || {});
    };

    getEmails("test.leco.nq");
  }, []);

  return (
    <div className="grid grid-rows-[20px_1fr_20px] items-center justify-items-center min-h-screen p-8 pb-20 gap-16 sm:p-20 font-[family-name:var(--font-geist-sans)]">
      {JSON.stringify(data)}
    </div>
  );
}
```

### Inserting a Notification

```typescript
const smsNotification: INSERT_NOTIFICATION_TYPE = {
  NotificationId: "12345",
  Message: "Your verification code is 123456",
  CustomerId: "98765"
  PhoneNo: "+1234567890",
};

await lecoNqDB.insertNotification(smsNotification);
```

### Retrieving a Notification by ID

```typescript
const notification = await lecoNqDB.getNotificationById("12345", "SMS");
console.log(notification);
```

### Updating a Notification Status

```typescript
await lecoNqDB.updateNotificationStatus({
  NotificationId: "12345",
  newStatus: "DELIVERED",
  type: "SMS",
});
```

### Searching for SMS Notifications by Phone Number

```typescript
const results = await lecoNqDB.searchSmsByPhoneNo({
  phone: "+1234567890",
  params: { per_page: 10 },
});
console.log(results);
```

### Fetching All Notifications

```typescript
await lecoNqDB.fetchAllNotifications({
  type: "EMAIL",
  batchSize: 50,
  onFetch: async (docs) => {
    console.log("Fetched batch:", docs);
  },
});
```

## API Reference

### Types

- `INSERT_NOTIFICATION_TYPE`: Structure for inserting notifications.
- `NOTIFICATION`: Enum type (`'SMS' | 'EMAIL'`).
- `UPDATE_NOTIFICATION_INFO_TYPE`: Structure for updating notification status.
- `FETCH_ALL_NOTIFICATIONS_PARAM_TYPE`: Parameters for fetching notifications.

### Methods

# Methods in `NotificationDBI`

## insertNotification

**Description:** Inserts a single notification record.  
**Parameters:** `sms: INSERT_NOTIFICATION_TYPE`  
**Returns:** `Promise<void>`

## insertNotificationBatch

**Description:** Inserts multiple notifications in a batch.  
**Parameters:** `smsList: INSERT_NOTIFICATION_TYPE[]`  
**Returns:** `Promise<void>`

## getNotificationById

**Description:** Retrieves a notification by ID.  
**Parameters:**

- `id: string`
- `type: NOTIFICATION`  
  **Returns:** `Promise<PromiseResult<DocumentClient.GetItemOutput, AWSError>>`

## searchSmsByPhoneNo

**Description:** Performs a fuzzy search for SMS notifications by phone number.  
**Parameters:**

- `info: { phone: string; params?: Omit<Partial<SearchParams>, "q" | "query_by">; }`  
  **Returns:** `Promise<SearchResponse<SMS_SCHEMA_TYPE>>`

## searchEmailByAddress

**Description:** Performs a fuzzy search for email notifications by email address.  
**Parameters:**

- `info: { email: string; params?: Omit<Partial<SearchParams>, "q" | "query_by">; }`  
  **Returns:** `Promise<SearchResponse<EMAIL_SCHEMA_TYPE>>`

## updateNotificationStatus

**Description:** Updates the status of a notification.  
**Parameters:** `notification: UPDATE_NOTIFICATION_INFO_TYPE`  
**Returns:** `Promise<UPDATE_STATUS_RETURN_TYPE<T>>`

## resetTypeSenseCollections

**Description:** Resets TypeSense collections.  
**Parameters:** `type: NOTIFICATION`  
**Returns:** `Promise<void>`

## deletedNotification

**Description:** Deletes a notification record.  
**Parameters:**

- `notification: { NotificationId: string; type: NOTIFICATION; }`  
  **Returns:** `Promise<void>`

## fetchAllNotifications

**Description:** Fetches all notifications with filters.  
**Parameters:** `params: FETCH_ALL_NOTIFICATIONS_PARAM_TYPE`  
**Returns:** `Promise<void>`

## recreateTypesenseIndecies

**Description:** Recreates TypeSense indices.  
**Parameters:** `type: NOTIFICATION`  
**Returns:** `Promise<void>`

## updateBatchNotificationStatus

**Description:** Updates multiple notifications in a batch.  
**Parameters:** `notifications: UPDATE_NOTIFICATION_INFO_TYPE[]`  
**Returns:** `Promise<void>`

## License

This package is licensed under the **MIT License**.

## Contributing

Contributions are welcome! Feel free to submit a pull request or report issues.