Select Git revision
newsletter.service.ts

Hugo SUBTIL authored
To find the state of this project's repository at the time of any of these versions, check out the tags.
newsletter.service.ts 1.75 KiB
import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { Model } from 'mongoose';
import { INewsletterSubscription } from './interface/newsletter-subscription.interface';
import { NewsletterSubscription, NewsletterSubscriptionDocument } from './newsletter-subscription.schema';
@Injectable()
export class NewsletterService {
constructor(
@InjectModel(NewsletterSubscription.name) private newsletterSubscriptionModel: Model<INewsletterSubscription>
) {}
public async newsletterSubscribe(email: string): Promise<NewsletterSubscription> {
const existingEmail = await this.findOne(email);
if (existingEmail) {
throw new HttpException('Email already exists', HttpStatus.BAD_REQUEST);
}
await this.newsletterSubscriptionModel.create({ email: email });
return this.findOne(email);
}
public async newsletterUnsubscribe(email: string): Promise<NewsletterSubscription> {
const subscription = await this.findOne(email);
if (!subscription) {
throw new HttpException('Invalid email', HttpStatus.BAD_REQUEST);
}
return subscription.deleteOne();
}
public async findOne(mail: string): Promise<INewsletterSubscription | undefined> {
return this.newsletterSubscriptionModel.findOne({ email: mail });
}
public async searchNewsletterSubscription(searchString: string): Promise<NewsletterSubscriptionDocument[]> {
return this.newsletterSubscriptionModel.find({ email: new RegExp(searchString, 'i') });
}
public async countNewsletterSubscriptions(): Promise<number> {
return this.newsletterSubscriptionModel.countDocuments({});
}
public async findAll(): Promise<NewsletterSubscription[]> {
return this.newsletterSubscriptionModel.find();
}
}