Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Queue Implementation #1

Merged
merged 2 commits into from
Jan 30, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
PORT=3000
MONGODB_URL=mongodb://127.0.0.1:27017/multiswap-node
QUEUE=Transaction
9 changes: 9 additions & 0 deletions .eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
node_modules
bin
# build artefacts
build/*
coverage/*
# data definition files
**/*.d.ts
# custom definition files
/src/types/
19 changes: 19 additions & 0 deletions .eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
{
"env": {
"browser": true,
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": "latest",
"sourceType": "module"
},
"plugins": [
"@typescript-eslint"
],
"rules": {}
}
25 changes: 25 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
# Dependencies
node_modules

# Ignore built ts files
build/**/*

# ingore redis database file
*.rdb

# ignore yarn.lock
yarn.lock

# yarn error logs
yarn-error.log

# Environment varibales
.env
.env.local
.env.development.local
.env.test.local
.env.production.local
!.env*.example

# Code coverage
coverage
1 change: 1 addition & 0 deletions .nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v18.12.1
3 changes: 3 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
build
coverage
14 changes: 14 additions & 0 deletions .prettierrc
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"quoteProps": "as-needed",
"jsxSingleQuote": false,
"trailingComma": "all",
"bracketSpacing": true,
"jsxBracketSameLine": true,
"arrowParens": "avoid",
"endOfLine": "auto"
}
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Getting Started

run `npm install` OR `yarn install` at the root of the repo.
36 changes: 36 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
{
"name": "multiswap-node",
"version": "1.0.0",
"description": "MultiSwap Node Cron",
"main": "src/index.ts",
"scripts": {
"start": "cross-env NODE_ENV=development nodemon build/index.js",
"build": "rm -rf ./build && tsc",
"dev": "cross-env NODE_ENV=development nodemon && ts-node src/index.ts",
"lint": "eslint .",
"lint:fix": "tsc --noEmit && eslint \"**/*.{js,ts}\" --quiet --fix",
"prettier": "prettier --check \"**/*.{js,ts}\"",
"prettier:fix": "prettier --write \"**/*.{js,ts}\""
},
"keywords": [],
"license": "MIT",
"devDependencies": {
"@types/express": "^4.17.13",
"@types/node": "^17.0.13",
"@typescript-eslint/eslint-plugin": "^5.10.1",
"@typescript-eslint/parser": "^5.10.1",
"cross-env": "^7.0.3",
"eslint": "^8.8.0",
"nodemon": "^2.0.15",
"prettier": "^2.5.1",
"ts-node": "^10.4.0",
"typescript": "^4.5.5"
},
"dependencies": {
"bullmq": "^3.5.11",
"dotenv": "^16.0.3",
"express": "^4.17.2",
"mongoose": "^6.9.0",
"web3": "^1.8.1"
}
}
21 changes: 21 additions & 0 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import express, { Request, Response, NextFunction, Application } from 'express';
import routes from './routes';

const app: Application = express();

// parse json request body
app.use(express.json());

// parse urlencoded request body
app.use(express.urlencoded({ extended: true }));

// v1 api routes
app.use('/', routes);

// send back a 404 error for any unknown api request
app.use((req: Request, res: Response, next: NextFunction) => {
console.log(req.path);
next(Error('Not found'));
});

export default app;
1 change: 1 addition & 0 deletions src/controllers/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * as jobController from './job.controller';
11 changes: 11 additions & 0 deletions src/controllers/job.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import { Request, Response } from 'express';
import { jobService } from '../services';

export const createJob = async (req: Request, res: Response): Promise<any> => {
try {
const job = await jobService.addJobs(req.body);
res.send(job.id);
} catch (err) {
console.error(err);
}
};
48 changes: 48 additions & 0 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import mongoose from 'mongoose';
import dotenv from 'dotenv';
import app from './app';
import './worker';
dotenv.config();

mongoose.set('strictQuery', true);
mongoose
.connect(process.env.MONGODB_URL as string)
.then(() => {
console.info('Connected to MongoDB');
})
.catch(err => {
console.error(
`MongoDB connection error. Please make sure MongoDB is running. ${err}`,
);
});

const server = app.listen(process.env.PORT, () => {
console.info(`Listening to port ${process.env.PORT}`);
});

const exitHandler = () => {
if (server) {
server.close(() => {
console.info('Server closed');
process.exit(1);
});
} else {
process.exit(1);
}
};

const unexpectedErrorHandler = (error: Error) => {
console.error(error);
exitHandler();
};

process.on('uncaughtException', unexpectedErrorHandler);
process.on('unhandledRejection', unexpectedErrorHandler);

process.on('SIGTERM', () => {
console.info('SIGTERM received');
if (server) {
server.close();
console.error('server closed');
}
});
17 changes: 17 additions & 0 deletions src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
import { Router } from 'express';
import jobRoute from './jobRouter.route';

const router = Router();

const defaultRoutes = [
{
path: '/jobs',
route: jobRoute,
},
];

defaultRoutes.forEach(route => {
router.use(route.path, route.route);
});

export default router;
8 changes: 8 additions & 0 deletions src/routes/jobRouter.route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { Router } from 'express';
import { jobController } from '../controllers';

const router = Router();

router.route('/').post(jobController.createJob);

export default router;
2 changes: 2 additions & 0 deletions src/services/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * as jobService from './job.service';
export * as web3Service from './web3.service';
10 changes: 10 additions & 0 deletions src/services/job.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import { Queue } from 'bullmq';
import dotenv from 'dotenv';
dotenv.config();

const queue = new Queue(process.env.QUEUE as string);

export const addJobs = async (jobBody: any) => {
const job = await queue.add(jobBody.name, jobBody.data);
return job;
};
13 changes: 13 additions & 0 deletions src/services/web3.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import Web3 from 'web3';

export const getTransactionReceipt = async (txId: string, rpcURL: string) => {
const web3 = new Web3(rpcURL);
let transaction: any;
while (
transaction &&
(transaction.status === null || transaction.status === 'pending')
) {
transaction = await web3.eth.getTransactionReceipt(txId);
}
return transaction;
};
18 changes: 18 additions & 0 deletions src/worker.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Worker } from 'bullmq';
import { web3Service } from './services';

const worker = new Worker(
process.env.QUEUE as string,
async job =>
await web3Service.getTransactionReceipt(job.data.txId, job.data.rpcURL),
);
worker.on('completed', job => {
console.log(`${job.id} has completed!`);
// return job.data;
});

worker.on('failed', (job: any, err) => {
console.log(`${job.id} has failed with ${err.message}`);
});

export default worker;
14 changes: 14 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"compilerOptions": {
"target": "es2016",
"module": "commonjs",
"moduleResolution": "node",
"resolveJsonModule": true,
"outDir": "build",
"esModuleInterop": true,
"forceConsistentCasingInFileNames": true,
"strict": true,
"noImplicitAny": true,
"skipLibCheck": true
}
}