Skip to content

Commit

Permalink
email services send email and get all email controller & routes added
Browse files Browse the repository at this point in the history
  • Loading branch information
zobkazi committed Apr 28, 2024
1 parent 143dc6e commit fb87886
Show file tree
Hide file tree
Showing 13 changed files with 143 additions and 10 deletions.
12 changes: 11 additions & 1 deletion packages/apiGateway/src/config.json
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,18 @@
}
]
},
"notification": {
"email" : {
"url": "http://localhost:4003",
"routes": [
{
"path": "/send-email",
"methods": ["post"],
"middlewares": []
}
]
},
"notification": {
"url": "http://localhost:4004",
"routes": [
{
"path": "/users/:id",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
-- CreateTable
CREATE TABLE "Email" (
"id" TEXT NOT NULL,
"sender" TEXT NOT NULL DEFAULT '',
"recipient" TEXT NOT NULL,
"subject" TEXT NOT NULL,
"body" TEXT NOT NULL,
"source" TEXT NOT NULL DEFAULT '',
"createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
"updatedAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,

CONSTRAINT "Email_pkey" PRIMARY KEY ("id")
);
3 changes: 3 additions & 0 deletions packages/services/email/prisma/migrations/migration_lock.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Please do not edit this file manually
# It should be added in your version-control system (i.e. Git)
provider = "postgresql"
11 changes: 11 additions & 0 deletions packages/services/email/prisma/schema.prisma
Original file line number Diff line number Diff line change
Expand Up @@ -12,3 +12,14 @@ datasource db {
provider = "postgresql"
url = env("DATABASE_URL")
}

model Email {
id String @id @default(cuid())
sender String @default("")
recipient String
subject String
body String
source String @default("")
createdAt DateTime @default(now())
updatedAt DateTime @default(now())
}
7 changes: 7 additions & 0 deletions packages/services/email/src/controllers/getEmails.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { Request, Response,NextFunction } from "express"

const getEmail = async (req: Request, res: Response, next: NextFunction) => {

}

export default getEmail
50 changes: 47 additions & 3 deletions packages/services/email/src/controllers/sendEmail.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Request, Response, NextFunction } from 'express';
import prisma from '@/utils/prisma';
import { EmailCreateSchema } from '@/utils/schemas';
import { emailCreateSchema } from '@/utils/schemas';
import { defaultSender, transporter } from '@/config';


Expand All @@ -9,12 +9,56 @@ import { defaultSender, transporter } from '@/config';
const sendEmail = async (req: Request, res: Response, next: NextFunction) => {
try {
// validate input the req body
const parsedBody = EmailCreateSchema.safeParse(req.body)
const parsedBody = emailCreateSchema.safeParse(req.body)

if (!parsedBody.success) {
return res.status(400).json(parsedBody.error.errors)
}

// create a new email option
const { sender, recipient, subject, body, source } = parsedBody.data
const from = sender || defaultSender

const emailOptions = {
from,
to: recipient,
subject,
text: body,

}

// send email

const { rejected } = await transporter.sendMail(emailOptions)
if(rejected.length){
console.log("Email not sent", rejected)
return res.status(500).json({
message: "Email not sent",
rejected
})
}

await prisma.email.create({
data: {
sender,
recipient,
subject,
body,
source
}
})

// return success

return res.status(200).json({
message: "Email sent"

})


} catch (error) {
next(error)
}
}
}

export default sendEmail
33 changes: 31 additions & 2 deletions packages/services/email/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,33 @@
import init from "./app";
import express from "express";
import dotenv from "dotenv";
import cors from "cors";
import morgan from "morgan";
import error = require("@/utils/error");

import router from "./routes";

init()
dotenv.config();

const app = express();
app.use(express.json());
app.use(cors());
app.use(morgan("dev"));

app.get("/health", (_req, res) => {
res.status(200).json({ status: "UP" });
});

// routes

app.use("/", router);

// handler
app.use(error.notFound);
app.use(error.serverError);

const port = process.env.PORT || 4000;
const serviceName = process.env.SERVICE_NAME || "Email-Service";

app.listen(port, () => {
console.log(`${serviceName} is running on port ${port}`);
});
9 changes: 9 additions & 0 deletions packages/services/email/src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
import express from "express";
const router = express.Router();
import { getEmails, sendEmail } from '@/controllers'


router.post('/emails/send', sendEmail)
router.get('/emails', getEmails)

export default router;
Empty file.
8 changes: 4 additions & 4 deletions packages/services/email/src/utils/schemas.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { z } from 'zod';

export const EmailCreateSchema = z.object({
recipient: z.string().email(),
export const emailCreateSchema = z.object({
sender: z.string().optional(),
recipient: z.string(),
subject: z.string(),
body: z.string(),
source: z.string(),
sender: z.string().email().optional(),
source: z.string().optional()
});
7 changes: 7 additions & 0 deletions packages/services/notification/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,13 @@ app.use(express.urlencoded({ extended: true }));
app.use(express.static("public"));


const port = process.env.PORT || 4004;


app.listen(port, () => {
console.log(`Notification service listening on port ${port}`);
})

app.get("/", (_req, res) => {
res.status(200).json({ status: "UP" });
})
Expand Down

0 comments on commit fb87886

Please sign in to comment.