feat: write a module for postal

This commit is contained in:
Kakious 2024-07-15 01:03:37 -04:00
parent 55bdec2dfe
commit ad811feff8
17 changed files with 10177 additions and 3 deletions

25
.eslintrc.js Normal file
View file

@ -0,0 +1,25 @@
module.exports = {
parser: '@typescript-eslint/parser',
parserOptions: {
project: 'tsconfig.json',
tsconfigRootDir: __dirname,
sourceType: 'module',
},
plugins: ['@typescript-eslint/eslint-plugin'],
extends: [
'plugin:@typescript-eslint/recommended',
'plugin:prettier/recommended',
],
root: true,
env: {
node: true,
jest: true,
},
ignorePatterns: ['.eslintrc.js'],
rules: {
'@typescript-eslint/interface-name-prefix': 'off',
'@typescript-eslint/explicit-function-return-type': 'off',
'@typescript-eslint/explicit-module-boundary-types': 'off',
'@typescript-eslint/no-explicit-any': 'off',
},
};

4
.prettierrc Normal file
View file

@ -0,0 +1,4 @@
{
"singleQuote": true,
"trailingComma": "all"
}

View file

@ -1,3 +1,73 @@
# nestjs-postal-client <p align="center">
<a href="http://nestjs.com/" target="blank"><img src="https://nestjs.com/img/logo-small.svg" width="200" alt="Nest Logo" /></a>
This is an API client for Postal. </p>
[circleci-image]: https://img.shields.io/circleci/build/github/nestjs/nest/master?token=abc123def456
[circleci-url]: https://circleci.com/gh/nestjs/nest
<p align="center">A progressive <a href="http://nodejs.org" target="_blank">Node.js</a> framework for building efficient and scalable server-side applications.</p>
<p align="center">
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/v/@nestjs/core.svg" alt="NPM Version" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/l/@nestjs/core.svg" alt="Package License" /></a>
<a href="https://www.npmjs.com/~nestjscore" target="_blank"><img src="https://img.shields.io/npm/dm/@nestjs/common.svg" alt="NPM Downloads" /></a>
<a href="https://circleci.com/gh/nestjs/nest" target="_blank"><img src="https://img.shields.io/circleci/build/github/nestjs/nest/master" alt="CircleCI" /></a>
<a href="https://coveralls.io/github/nestjs/nest?branch=master" target="_blank"><img src="https://coveralls.io/repos/github/nestjs/nest/badge.svg?branch=master#9" alt="Coverage" /></a>
<a href="https://discord.gg/G7Qnnhy" target="_blank"><img src="https://img.shields.io/badge/discord-online-brightgreen.svg" alt="Discord"/></a>
<a href="https://opencollective.com/nest#backer" target="_blank"><img src="https://opencollective.com/nest/backers/badge.svg" alt="Backers on Open Collective" /></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://opencollective.com/nest/sponsors/badge.svg" alt="Sponsors on Open Collective" /></a>
<a href="https://paypal.me/kamilmysliwiec" target="_blank"><img src="https://img.shields.io/badge/Donate-PayPal-ff3f59.svg"/></a>
<a href="https://opencollective.com/nest#sponsor" target="_blank"><img src="https://img.shields.io/badge/Support%20us-Open%20Collective-41B883.svg" alt="Support us"></a>
<a href="https://twitter.com/nestframework" target="_blank"><img src="https://img.shields.io/twitter/follow/nestframework.svg?style=social&label=Follow"></a>
</p>
<!--[![Backers on Open Collective](https://opencollective.com/nest/backers/badge.svg)](https://opencollective.com/nest#backer)
[![Sponsors on Open Collective](https://opencollective.com/nest/sponsors/badge.svg)](https://opencollective.com/nest#sponsor)-->
## Description
[Nest](https://github.com/nestjs/nest) framework TypeScript starter repository.
## Installation
```bash
$ npm install
```
## Running the app
```bash
# development
$ npm run start
# watch mode
$ npm run start:dev
# production mode
$ npm run start:prod
```
## Test
```bash
# unit tests
$ npm run test
# e2e tests
$ npm run test:e2e
# test coverage
$ npm run test:cov
```
## Support
Nest is an MIT-licensed open source project. It can grow thanks to the sponsors and support by the amazing backers. If you'd like to join them, please [read more here](https://docs.nestjs.com/support).
## Stay in touch
- Author - [Kamil Myśliwiec](https://kamilmysliwiec.com)
- Website - [https://nestjs.com](https://nestjs.com/)
- Twitter - [@nestframework](https://twitter.com/nestframework)
## License
Nest is [MIT licensed](LICENSE).

8
nest-cli.json Normal file
View file

@ -0,0 +1,8 @@
{
"$schema": "https://json.schemastore.org/nest-cli",
"collection": "@nestjs/schematics",
"sourceRoot": "src",
"compilerOptions": {
"deleteOutDir": true
}
}

9658
package-lock.json generated Normal file

File diff suppressed because it is too large Load diff

77
package.json Normal file
View file

@ -0,0 +1,77 @@
{
"name": "nestjs-postal-client",
"version": "0.0.1",
"description": "",
"author": "",
"private": true,
"license": "UNLICENSED",
"scripts": {
"build": "nest build",
"format": "prettier --write \"src/**/*.ts\" \"test/**/*.ts\"",
"start": "nest start",
"start:dev": "nest start --watch",
"start:debug": "nest start --debug --watch",
"start:prod": "node dist/main",
"lint": "eslint \"{src,apps,libs,test}/**/*.ts\" --fix",
"test": "jest",
"test:watch": "jest --watch",
"test:cov": "jest --coverage",
"test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand",
"test:e2e": "jest --config ./test/jest-e2e.json",
"prepare": "ts-patch install && typia patch"
},
"dependencies": {
"@furality/nestjs-http-promise": "^2.0.97",
"@nestjs/common": "^10.0.0",
"@nestjs/core": "^10.0.0",
"@nestjs/platform-express": "^10.0.0",
"@opentelemetry/api": "^1.9.0",
"axios": "^1.7.2",
"axios-retry": "^4.4.1",
"nestjs-otel": "^6.1.1",
"reflect-metadata": "^0.2.0",
"rxjs": "^7.8.1",
"typia": "^6.5.1"
},
"devDependencies": {
"@nestjs/cli": "^10.0.0",
"@nestjs/schematics": "^10.0.0",
"@nestjs/testing": "^10.0.0",
"@types/express": "^4.17.17",
"@types/jest": "^29.5.2",
"@types/node": "^20.3.1",
"@types/supertest": "^6.0.0",
"@typescript-eslint/eslint-plugin": "^7.0.0",
"@typescript-eslint/parser": "^7.0.0",
"eslint": "^8.42.0",
"eslint-config-prettier": "^9.0.0",
"eslint-plugin-prettier": "^5.0.0",
"jest": "^29.5.0",
"prettier": "^3.0.0",
"source-map-support": "^0.5.21",
"supertest": "^7.0.0",
"ts-jest": "^29.1.0",
"ts-loader": "^9.4.3",
"ts-node": "^10.9.1",
"ts-patch": "^3.2.1",
"tsconfig-paths": "^4.2.0",
"typescript": "^5.5.2"
},
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "src",
"testRegex": ".*\\.spec\\.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"collectCoverageFrom": [
"**/*.(t|j)s"
],
"coverageDirectory": "../coverage",
"testEnvironment": "node"
}
}

5
src/index.ts Normal file
View file

@ -0,0 +1,5 @@
export * from './postal.constant';
export * from './postal.interface';
export { PostalClientModule } from './postal.module';
export { PostalClientService } from './postal.service';
export * from './interface';

View file

@ -0,0 +1,12 @@
export enum ErrorType {
ValidationError = 'ValidationError',
NoRecipients = 'NoRecipients',
NoContent = 'NoContent',
TooManyToAddresses = 'TooManyToAddresses',
TooManyCCAddresses = 'TooManyCCAddresses',
TooManyBCCAddresses = 'TooManyBCCAddresses',
FromAddressMissing = 'FromAddressMissing',
UnauthenticatedFromAddress = 'UnauthenticatedFromAddress',
AttatchmentMissingName = 'AttatchmentMissingName',
AttachmentMissingData = 'AttachmentMissingData',
}

2
src/interface/index.ts Normal file
View file

@ -0,0 +1,2 @@
export * from './send.interface';
export * from './error.interface';

View file

@ -0,0 +1,38 @@
import type { tags } from 'typia';
import typia from 'typia';
export const validateSendMessage = typia.createAssertGuard<SendMessage>();
export type SendMessage = {
// The e-mail addresses of the recipients (max 50)
to: Array<string> & tags.MaxItems<50> & tags.MinItems<1>;
// The e-mail addresses of any CC contacts (max 50)
cc?: Array<string> & tags.MaxItems<50> & tags.MinItems<1>;
// The e-mail addresses of any BCC contacts (max 50)
bcc?: Array<string> & tags.MaxItems<50> & tags.MinItems<1>;
// The e-mail address for the From header
from: string;
// The e-mail address for the Sender header
sender?: string;
// The subject of the e-mail
subject?: string;
//The tag of the email
tag?: string;
// Reply to email address
reply_to?: string;
// The Plain Text content of the e-mail
plain_body: string;
// The HTML content of the e-mail
html_body?: string;
//An array of attachments
attachments?: Array<any>;
//Additional headers to add to the e-mail
headers?: any;
//Is this message a bounce?
bounce?: boolean;
};

12
src/postal.constant.ts Normal file
View file

@ -0,0 +1,12 @@
export const POSTAL_HTTP_SERVICE = Symbol('POSTAL_HTTP_SERVICE');
export const POSTAL_CONFIG_OPTIONS = Symbol('POSTAL_CONFIG_OPTIONS');
// API Endpoints
// Sending Messages API
export const SEND_MESSAGE_API_URL = '/api/v1/send/message';
export const SEND_MESSAGE_RAW_API_URL = '/api/v1/send/raw';
// Message Status API
export const RETURN_MESSAGE_API_URL = '/api/v1/messages/message';
export const RETURN_DELIVERY_API_URL = '/api/v1/messages/deliveries';

37
src/postal.interface.ts Normal file
View file

@ -0,0 +1,37 @@
import type {
InjectionToken,
ModuleMetadata,
OptionalFactoryDependency,
Provider,
Type,
} from '@nestjs/common';
import type { AxiosRequestConfig } from 'axios';
import { IAxiosRetryReturn } from 'axios-retry';
import { createAssert } from 'typia';
export interface PostalServiceOptions {
baseURL: string;
apiKey: string;
}
export const assertPostalServiceOptions = createAssert<PostalServiceOptions>();
export interface PostalModuleOptions {
http: Omit<AxiosRequestConfig, 'baseUrl'> & IAxiosRetryReturn;
postal: PostalServiceOptions;
}
export interface PostalModuleOptionsFactory {
createPostalOptions(): Promise<PostalModuleOptions> | PostalModuleOptions;
}
export interface PostalModuleAsyncOptions
extends Pick<ModuleMetadata, 'imports'> {
useExisting?: Type<PostalModuleOptionsFactory>;
useClass?: Type<PostalModuleOptionsFactory>;
useFactory?: (
...args: any[]
) => Promise<PostalModuleOptions> | PostalModuleOptions;
inject?: (InjectionToken | OptionalFactoryDependency)[];
extraProviders?: Provider[];
}

124
src/postal.module.ts Normal file
View file

@ -0,0 +1,124 @@
import { HttpModule, HttpService } from '@furality/nestjs-http-promise';
import type { DynamicModule, Provider } from '@nestjs/common';
import { Module } from '@nestjs/common';
import http from 'http';
import https from 'https';
import { POSTAL_HTTP_SERVICE, POSTAL_CONFIG_OPTIONS } from './postal.constant';
import type {
PostalModuleAsyncOptions,
PostalModuleOptionsFactory,
PostalModuleOptions,
} from './postal.interface';
import { PostalClientService } from './postal.service';
@Module({})
export class PostalClientModule {
static register(config: PostalModuleOptions): DynamicModule {
return {
module: PostalClientModule,
imports: [
HttpModule.register({
baseURL: config.postal.baseURL,
...config.http,
}),
],
providers: [
PostalClientService,
{
provide: POSTAL_CONFIG_OPTIONS,
useValue: config.postal,
},
],
exports: [PostalClientService],
};
}
static registerAsync(asyncOptions: PostalModuleAsyncOptions): DynamicModule {
const providers = this.createAsyncProviders(asyncOptions);
return {
module: PostalClientModule,
imports: [
HttpModule.registerAsync({
...(asyncOptions.imports && { imports: asyncOptions.imports }),
useFactory: (options: PostalModuleOptions) => ({
httpAgent: new http.Agent({
keepAlive: true,
keepAliveMsecs: 10 * 60 * 1000,
}),
httpsAgent: new https.Agent({
keepAlive: true,
keepAliveMsecs: 10 * 60 * 1000,
}),
baseURL: options.postal.baseURL,
...options.http,
}),
inject: [POSTAL_CONFIG_OPTIONS],
extraProviders: providers,
}),
...(asyncOptions.imports ?? []),
],
providers: [
PostalClientService,
{
provide: POSTAL_CONFIG_OPTIONS,
useFactory: (options: PostalModuleOptions) => options.postal,
inject: [POSTAL_CONFIG_OPTIONS],
},
{
provide: POSTAL_HTTP_SERVICE,
useExisting: HttpService,
},
...providers,
],
exports: [PostalClientService, POSTAL_HTTP_SERVICE],
};
}
private static createAsyncProviders(
options: PostalModuleAsyncOptions,
): Provider[] {
if (!!options.useExisting || !!options.useFactory) {
return [this.createAsyncOptionsProvider(options)];
}
const providers = [this.createAsyncOptionsProvider(options)];
if (options.useClass) {
providers.push({
provide: options.useClass,
useClass: options.useClass,
});
}
return providers;
}
private static createAsyncOptionsProvider(
options: PostalModuleAsyncOptions,
): Provider {
if (options.useFactory) {
return {
provide: POSTAL_CONFIG_OPTIONS,
useFactory: options.useFactory,
inject: options.inject ?? [],
};
}
const inject = options.useExisting
? [options.useExisting]
: options.useClass
? [options.useClass]
: null;
return {
provide: POSTAL_CONFIG_OPTIONS,
useFactory: async (optionsFactory: PostalModuleOptionsFactory) =>
await optionsFactory.createPostalOptions(),
...(inject && { inject }),
};
}
}

39
src/postal.service.ts Normal file
View file

@ -0,0 +1,39 @@
import { Inject, Injectable } from '@nestjs/common';
import {
POSTAL_CONFIG_OPTIONS,
POSTAL_HTTP_SERVICE,
SEND_MESSAGE_API_URL,
} from './postal.constant';
import { HttpService } from '@furality/nestjs-http-promise';
import { PostalServiceOptions } from './postal.interface';
import { Span } from 'nestjs-otel';
import { SpanKind } from '@opentelemetry/api';
import { SendMessage } from './interface/send.interface';
@Injectable()
export class PostalClientService {
constructor(
@Inject(POSTAL_HTTP_SERVICE) private readonly httpService: HttpService,
@Inject(POSTAL_CONFIG_OPTIONS)
private readonly config: PostalServiceOptions,
) {}
@Span(undefined, { kind: SpanKind.CLIENT })
async sendMessage(message: SendMessage): Promise<any> {
const response = await this.httpService.post(
SEND_MESSAGE_API_URL,
message,
{
headers: {
'X-Postal-Api-Key': this.config.apiKey,
},
},
);
const { data } = response;
if (data.status === 'error') {
throw new Error(data.data.message);
}
}
}

13
src/utils/axios.util.ts Normal file
View file

@ -0,0 +1,13 @@
import type { AxiosError } from 'axios';
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export function isAxiosError<T = any, D = any>(
payload: unknown,
): payload is AxiosError<T, D> {
return (
typeof payload === 'object' &&
!!payload &&
'name' in payload &&
payload.name === 'AxiosError'
);
}

24
src/utils/type.util.ts Normal file
View file

@ -0,0 +1,24 @@
export type RequiredBy<T, K extends keyof T> = Omit<T, K> &
Pick<Required<T>, K>;
export type RequireAtLeastOne<T, Keys extends keyof T = keyof T> = Pick<
T,
Exclude<keyof T, Keys>
> &
{
[K in Keys]-?: Required<Pick<T, K>> & Partial<Pick<T, Exclude<Keys, K>>>;
}[Keys];
export function hasProperties<T extends object, K extends keyof T>(
obj: T | RequiredBy<T, K>,
...keys: readonly K[]
): obj is RequiredBy<T, K> {
return keys.every((x) => obj[x] !== undefined);
}
export function hasAtLeastOneProperty<T extends object, K extends keyof T>(
obj: T | RequireAtLeastOne<T, K>,
...keys: readonly K[]
): obj is RequireAtLeastOne<T, K> {
return keys.some((x) => obj[x] !== undefined);
}

26
tsconfig.json Normal file
View file

@ -0,0 +1,26 @@
{
"compilerOptions": {
"module": "commonjs",
"declaration": true,
"removeComments": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"allowSyntheticDefaultImports": true,
"target": "ES2021",
"sourceMap": true,
"outDir": "./dist",
"baseUrl": "./",
"incremental": true,
"skipLibCheck": true,
"strictNullChecks": true,
"noImplicitAny": false,
"strictBindCallApply": false,
"forceConsistentCasingInFileNames": false,
"noFallthroughCasesInSwitch": false,
"plugins": [
{
"transform": "typia/lib/transform"
}
]
}
}