Skip to content

Commit

Permalink
prettier
Browse files Browse the repository at this point in the history
  • Loading branch information
cyri113 committed May 21, 2023
1 parent f03809e commit 9050974
Show file tree
Hide file tree
Showing 23 changed files with 124 additions and 127 deletions.
2 changes: 1 addition & 1 deletion __test__/controllers/jobs/createJob.controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { type Queue } from "bullmq";
import { queueByName } from "../../../src/queues";
import createJob from "../../../src/controllers/jobs/createJob.controller";

console.error = jest.fn()
console.error = jest.fn();

// Mock the queueByName function
jest.mock("../../../src/queues", () => ({
Expand Down
6 changes: 4 additions & 2 deletions __test__/controllers/jobs/getJob.controller.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ describe("getJob", () => {

beforeEach(() => {
req = {
params: {}
params: {},
} as Request;
res = {
json: jest.fn(),
Expand Down Expand Up @@ -105,6 +105,8 @@ describe("getJob", () => {
await getJob(req, res);

expect(res.status).toHaveBeenCalledWith(500);
expect(res.json).toHaveBeenCalledWith({ error: "Failed to get job status" });
expect(res.json).toHaveBeenCalledWith({
error: "Failed to get job status",
});
});
});
8 changes: 4 additions & 4 deletions __test__/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ console.log = jest.fn();
// Mock mongoose.connect and app.listen
jest.mock("mongoose", () => ({
set: jest.fn(),
connect: jest.fn()
connect: jest.fn(),
}));
jest.mock("../src/app", () => ({
listen: jest.fn(),
Expand All @@ -29,7 +29,7 @@ describe("main", () => {
});

it("should connect to MongoDB and start the server", async () => {
await expect(require("../src/index").main()).resolves.not.toThrow()
await expect(require("../src/index").main()).resolves.not.toThrow();

expect(mongoose.set).toHaveBeenCalledWith("strictQuery", true);
expect(mongoose.connect).toHaveBeenCalledWith("mocked-mongodb-url");
Expand All @@ -38,8 +38,8 @@ describe("main", () => {
});

it("should handle errors and log them", async () => {
const error = new Error("Connection failed")
mongoose.connect = jest.fn().mockRejectedValueOnce(error)
const error = new Error("Connection failed");
mongoose.connect = jest.fn().mockRejectedValueOnce(error);
await expect(require("../src/index").main()).rejects.toThrow(error);

expect(mongoose.connect).toHaveBeenCalledWith("mocked-mongodb-url");
Expand Down
31 changes: 16 additions & 15 deletions __test__/jobs/email.job.test.ts
Original file line number Diff line number Diff line change
@@ -1,39 +1,40 @@
import { type Job } from 'bullmq';
import emailJob from '../../src/jobs/email.job';
import { type Job } from "bullmq";
import emailJob from "../../src/jobs/email.job";

describe('emailJob', () => {
describe("emailJob", () => {
let consoleLogSpy: jest.SpyInstance;
let consoleErrorSpy: jest.SpyInstance;

beforeEach(() => {
consoleLogSpy = jest.spyOn(console, 'log');
consoleErrorSpy = jest.spyOn(console, 'error');
consoleLogSpy = jest.spyOn(console, "log");
consoleErrorSpy = jest.spyOn(console, "error");
});

afterEach(() => {
consoleLogSpy.mockRestore();
consoleErrorSpy.mockRestore();
});

it('should process email job successfully', async () => {
it("should process email job successfully", async () => {
const jobData = {
to: '[email protected]',
subject: 'Test Subject',
body: 'Test Body',
to: "[email protected]",
subject: "Test Subject",
body: "Test Body",
};

const job: Partial<Job> = {
id: 'jobId',
id: "jobId",
data: jobData,
name: 'emailJob',
name: "emailJob",
};

await emailJob(job as Job);

expect(consoleLogSpy).toHaveBeenCalledWith(`Sending email to ${jobData.to}: ${jobData.subject}`);
expect(consoleLogSpy).toHaveBeenCalledWith('Body:', jobData.body);
expect(consoleLogSpy).toHaveBeenCalledWith('Email sent successfully');
expect(consoleLogSpy).toHaveBeenCalledWith(
`Sending email to ${jobData.to}: ${jobData.subject}`
);
expect(consoleLogSpy).toHaveBeenCalledWith("Body:", jobData.body);
expect(consoleLogSpy).toHaveBeenCalledWith("Email sent successfully");
expect(consoleErrorSpy).not.toHaveBeenCalled();
});

});
14 changes: 7 additions & 7 deletions __test__/jobs/imageProcessing.job.test.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import { type Job } from 'bullmq';
import imageProcessingJob from '../../src/jobs/imageProcessing.job';
import { type Job } from "bullmq";
import imageProcessingJob from "../../src/jobs/imageProcessing.job";

describe('imageProcessingJob', () => {
it('should process the image successfully', async () => {
const imageUrl = 'https://example.com/image.jpg';
describe("imageProcessingJob", () => {
it("should process the image successfully", async () => {
const imageUrl = "https://example.com/image.jpg";
const jobData = { imageUrl };
const job: Partial<Job> = {
id: 'job-id',
name: 'image-processing',
id: "job-id",
name: "image-processing",
data: jobData,
// Mock other attributes as needed
};
Expand Down
36 changes: 18 additions & 18 deletions __test__/workers/email.worker.test.ts
Original file line number Diff line number Diff line change
@@ -1,28 +1,28 @@
import { Worker } from 'bullmq'
import { emailQueue } from '../../src/queues';
import connection from '../../src/queues/connection';
import { Worker } from "bullmq";
import { emailQueue } from "../../src/queues";
import connection from "../../src/queues/connection";

jest.mock('bullmq', () => ({
jest.mock("bullmq", () => ({
...jest.requireActual("bullmq"),
Worker: jest.fn().mockImplementation((queueName, processingFunction, options) => {
const workerMock = {
on: jest.fn(),
};
return workerMock;
}),
Worker: jest
.fn()
.mockImplementation((queueName, processingFunction, options) => {
const workerMock = {
on: jest.fn(),
};
return workerMock;
}),
}));

describe('email.worker', () => {
describe("email.worker", () => {
afterEach(() => {
jest.clearAllMocks();
});

it('should create a new BullMQ worker for emailQueue', async () => {
require('../../src/workers/email.worker')
expect(Worker).toHaveBeenCalledWith(
emailQueue.name,
expect.any(Function),
{ connection }
);
it("should create a new BullMQ worker for emailQueue", async () => {
require("../../src/workers/email.worker");
expect(Worker).toHaveBeenCalledWith(emailQueue.name, expect.any(Function), {
connection,
});
});
});
4 changes: 2 additions & 2 deletions src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@ import express, { type Express, type Request, type Response } from "express";
import routes from "./routes";

const app: Express = express();
app.use(express.json())
app.use(routes)
app.use(express.json());
app.use(routes);

app.get("/", (req: Request, res: Response) => {
res.send("Express + TypeScript Server");
Expand Down
14 changes: 7 additions & 7 deletions src/controllers/jobs/createJob.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,21 +7,21 @@ const createJob = async function (req: Request, res: Response) {
try {
const { type, data } = req.body; // Assuming you send the job type and data in the request body

let queue: Queue
let queue: Queue;
try {
queue = queueByName(type)
queue = queueByName(type);
} catch (error) {
console.error(error)
console.error(error);
return res.status(400).json({ error });
}

const job = await queue.add(type, data); // Add the job to the appropriate queue

return res.json({ jobId: job.id });
} catch (error) {
console.error('Error creating job:', error);
return res.status(500).json({ error: 'Failed to create job' });
console.error("Error creating job:", error);
return res.status(500).json({ error: "Failed to create job" });
}
}
};

export default createJob
export default createJob;
16 changes: 8 additions & 8 deletions src/controllers/jobs/getJob.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,19 @@ const getJob = async function (req: Request, res: Response) {
try {
const { type, jobId } = req.params; // Assuming the jobId is passed as a route parameter

let queue: Queue
let queue: Queue;
try {
queue = queueByName(type)
queue = queueByName(type);
} catch (error) {
console.error('Error getting job queue:', error)
console.error("Error getting job queue:", error);
return res.status(400).json({ error });
}

// Fetch the job by its id
const job = await Job.fromId(queue, jobId);

if (job == null) {
return res.status(404).json({ error: 'Job not found' });
return res.status(404).json({ error: "Job not found" });
}

return res.json({
Expand All @@ -30,9 +30,9 @@ const getJob = async function (req: Request, res: Response) {
data: job.data,
});
} catch (error) {
console.error('Error getting job status:', error);
return res.status(500).json({ error: 'Failed to get job status' });
console.error("Error getting job status:", error);
return res.status(500).json({ error: "Failed to get job status" });
}
}
};

export default getJob
export default getJob;
5 changes: 1 addition & 4 deletions src/controllers/jobs/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,4 @@
import createJob from "./createJob.controller";
import getJob from "./getJob.controller";

export {
createJob,
getJob
}
export { createJob, getJob };
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import mongoose from "mongoose";
import app from "./app";
import { env } from "./config";
import './workers'
import "./workers";

mongoose.set("strictQuery", true);

Expand Down
14 changes: 7 additions & 7 deletions src/jobs/email.job.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
/* eslint-disable @typescript-eslint/restrict-template-expressions */
import { type Job } from 'bullmq';
import { type Job } from "bullmq";

const emailJob = async (job: Job): Promise<void> => {
// Define the processing logic for email jobs
Expand All @@ -8,16 +8,16 @@ const emailJob = async (job: Job): Promise<void> => {
try {
// Perform email processing logic here
console.log(`Sending email to ${to}: ${subject}`);
console.log('Body:', body);
console.log("Body:", body);

// Simulating email sending time
await new Promise((resolve) => setTimeout(resolve, 2000));

console.log('Email sent successfully');
console.log("Email sent successfully");
} catch (error) {
console.error('Error processing email:', error);
throw new Error('Failed to process email'); // Throw an error if email processing fails
console.error("Error processing email:", error);
throw new Error("Failed to process email"); // Throw an error if email processing fails
}
}
};

export default emailJob
export default emailJob;
10 changes: 5 additions & 5 deletions src/jobs/imageProcessing.job.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,11 @@ const imageProcessingJob = async function (job: Job): Promise<void> {
// Simulating image processing time
await new Promise((resolve) => setTimeout(resolve, 3000));

console.log('Image processing completed');
console.log("Image processing completed");
} catch (error) {
console.error('Error processing image:', error);
throw new Error('Failed to process image'); // Throw an error if image processing fails
console.error("Error processing image:", error);
throw new Error("Failed to process image"); // Throw an error if image processing fails
}
}
};

export default imageProcessingJob
export default imageProcessingJob;
6 changes: 3 additions & 3 deletions src/queues/connection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { env } from "../config";

const connection: RedisOptions = {
host: env.REDIS_QUEUE_HOST,
port: env.REDIS_QUEUE_PORT
}
port: env.REDIS_QUEUE_PORT,
};

export default connection
export default connection;
4 changes: 2 additions & 2 deletions src/queues/email.queue.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Queue } from "bullmq";
import connection from "./connection";

const emailQueue = new Queue('email', { connection })
const emailQueue = new Queue("email", { connection });

export default emailQueue;
export default emailQueue;
4 changes: 2 additions & 2 deletions src/queues/imageProcessing.queue.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Queue } from "bullmq";
import connection from "./connection";

const imageProcessingQueue = new Queue('imageProcessing', { connection })
const imageProcessingQueue = new Queue("imageProcessing", { connection });

export default imageProcessingQueue;
export default imageProcessingQueue;
8 changes: 2 additions & 6 deletions src/queues/index.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,5 @@
import emailQueue from "./email.queue";
import imageProcessingQueue from "./imageProcessing.queue"
import imageProcessingQueue from "./imageProcessing.queue";
import queueByName from "./queueByName";

export {
emailQueue,
imageProcessingQueue,
queueByName
}
export { emailQueue, imageProcessingQueue, queueByName };
20 changes: 10 additions & 10 deletions src/queues/queueByName.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@ import emailQueue from "./email.queue";
import imageProcessingQueue from "./imageProcessing.queue";

const queueByName = (name: string): Queue => {
switch (name) {
case emailQueue.name:
return emailQueue;
case imageProcessingQueue.name:
return imageProcessingQueue;
default:
throw new Error(`No Queue called ${name}`)
}
}
switch (name) {
case emailQueue.name:
return emailQueue;
case imageProcessingQueue.name:
return imageProcessingQueue;
default:
throw new Error(`No Queue called ${name}`);
}
};

export default queueByName
export default queueByName;
Loading

0 comments on commit 9050974

Please sign in to comment.