Skip to content

Commit

Permalink
Merge pull request #12 from eusoff-hackers/fix/jersey-bidding
Browse files Browse the repository at this point in the history
Jersey Bidding code reuse
  • Loading branch information
juancarlovieri authored Oct 13, 2024
2 parents 268d45a + 8ea1551 commit 76d7acf
Show file tree
Hide file tree
Showing 37 changed files with 589 additions and 462 deletions.
5 changes: 3 additions & 2 deletions .eslintrc.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ module.exports = {
allowImportExportEverywhere: false,
},
parser: "@typescript-eslint/parser",
plugins: ["unused-imports", "no-relative-import-paths", "@typescript-eslint"],
plugins: ["unused-imports", "no-relative-import-paths", "@typescript-eslint", "import"],
rules: {
"@typescript-eslint/consistent-type-imports": "error",
"unused-imports/no-unused-imports": "error",
Expand All @@ -42,7 +42,7 @@ module.exports = {
"no-relative-import-paths/no-relative-import-paths": ["error", { prefix: "@" }],
"import/no-dynamic-require": 0,
"no-underscore-dangle": ["error", { allow: ["_id"] }],

"import/no-unassigned-import": "error",
"prettier/prettier": [
"error",
{
Expand All @@ -58,5 +58,6 @@ module.exports = {
extensions: [".js", ".jsx", ".ts", ".tsx"],
},
},
"import/no-unassigned-import": {},
},
};
14 changes: 6 additions & 8 deletions .vscode/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,7 @@
"editor.codeActionsOnSave": {
"source.fixAll.eslint": "explicit"
},
"eslint.validate": [
"javascript",
"javascriptreact",
"typescript",
"typescriptreact"
],
"eslint.validate": ["javascript", "javascriptreact", "typescript", "typescriptreact"],
"typescript.preferences.importModuleSpecifier": "non-relative",
"typescript.tsdk": "node_modules/typescript/lib",
"[typescript]": {
Expand All @@ -31,8 +26,11 @@
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
},
"files.associations": {
"files.associations": {
".env.development.local": "properties"
},

"files.exclude": {
"node_modules/": true,
"build/": true
}
}
53 changes: 25 additions & 28 deletions App.ts
Original file line number Diff line number Diff line change
@@ -1,24 +1,24 @@
import { JsonSchemaToTsProvider } from '@fastify/type-provider-json-schema-to-ts';
import Fastify from 'fastify';
import mongoose from 'mongoose';
import fastifySession from '@fastify/session';
import fastifyCookie from '@fastify/cookie';
import MongoStore from 'connect-mongo';
import IORedis from 'ioredis';
import Formbody from '@fastify/formbody';
import RedisStore from 'connect-redis';
import { MongoClient } from 'mongodb';
import redis from '@fastify/redis';
import caching from '@fastify/caching';
import cors from '@fastify/cors';
import crypto from 'crypto';
import v2 from './v2/routes/router';
import { logger, reportError } from './v2/utils/logger';
import v2 from "@/v2/routes/router";
import { logger, reportError } from "@/v2/utils/logger";
import caching from "@fastify/caching";
import fastifyCookie from "@fastify/cookie";
import cors from "@fastify/cors";
import Formbody from "@fastify/formbody";
import redis from "@fastify/redis";
import fastifySession from "@fastify/session";
import type { JsonSchemaToTsProvider } from "@fastify/type-provider-json-schema-to-ts";
import MongoStore from "connect-mongo";
import RedisStore from "connect-redis";
import crypto from "crypto";
import Fastify from "fastify";
import IORedis from "ioredis";
import { MongoClient } from "mongodb";
import mongoose from "mongoose";

const { env } = process;
const LOG_LEVEL: boolean = env.NODE_ENV !== 'production';
const LOG_LEVEL: boolean = env.NODE_ENV !== "production";

const abcache = require('abstract-cache'); // eslint-disable-line @typescript-eslint/no-var-requires
const abcache = require("abstract-cache"); // eslint-disable-line @typescript-eslint/no-var-requires
// const v1 = require(`./v1/routes/router.js`);

const secret = env.SESSION_SECRET || crypto.randomBytes(128).toString(`base64`);
Expand All @@ -29,10 +29,7 @@ const fastify = Fastify({

async function run() {
try {
await Promise.allSettled([
mongoose.connect(env.MONGO_URI),
fastify.listen(env.BACKEND_PORT, `0.0.0.0`),
]);
await Promise.allSettled([mongoose.connect(env.MONGO_URI), fastify.listen(env.BACKEND_PORT, `0.0.0.0`)]);

logger.info(`Connected to Atlas.`);
logger.info(`Server started, listening to ${env.BACKEND_PORT}`);
Expand All @@ -45,12 +42,12 @@ async function run() {
async function register() {
try {
fastify.register(cors, {
origin: env.FRONTEND_URL.split(','),
methods: ['GET', 'PUT', 'POST'],
allowedHeaders: ['Content-Type', 'Authorization', 'x-csrf-token'],
origin: env.FRONTEND_URL.split(","),
methods: ["GET", "PUT", "POST"],
allowedHeaders: ["Content-Type", "Authorization", "x-csrf-token"],
credentials: true,
maxAge: 600,
exposedHeaders: ['*', 'Authorization'],
exposedHeaders: ["*", "Authorization"],
});

fastify.register(fastifyCookie);
Expand All @@ -61,7 +58,7 @@ async function register() {
const abcacheClient = abcache({
useAwait: true,
driver: {
name: 'abstract-cache-redis',
name: "abstract-cache-redis",
options: { client: redisClient },
},
});
Expand All @@ -76,7 +73,7 @@ async function register() {
ttl: 14 * 24 * 60 * 60,
}),
cookie: {
sameSite: 'none',
sameSite: "none",
secure: true,
},
});
Expand Down
60 changes: 0 additions & 60 deletions v2/controllers/bid/info.ts

This file was deleted.

41 changes: 28 additions & 13 deletions v2/controllers/bid/create.ts → v2/controllers/jersey/bid.ts
Original file line number Diff line number Diff line change
@@ -1,12 +1,13 @@
import { Bid } from "@/v2/models/bid";
import type { iJersey } from "@/v2/models/jersey";
import { Jersey } from "@/v2/models/jersey";
import type { iJersey } from "@/v2/models/jersey/jersey";
import { Jersey } from "@/v2/models/jersey/jersey";
import { JerseyBid } from "@/v2/models/jersey/jerseyBid";
import { Server } from "@/v2/models/server";
import { auth } from "@/v2/plugins/auth";
import { isEligible } from "@/v2/utils/jersey";
import { logEvent, reportError } from "@/v2/utils/logger";
import { logAndThrow, logEvent, reportError } from "@/v2/utils/logger";
import { sendError, sendStatus } from "@/v2/utils/req_handler";
import type { FastifyReply, FastifyRequest, RouteOptions } from "fastify";
import type { IncomingMessage, Server, ServerResponse } from "http";
import type { Server as HttpServer, IncomingMessage, ServerResponse } from "http";
import type { FromSchema } from "json-schema-to-ts";

const schema = {
Expand Down Expand Up @@ -34,21 +35,35 @@ async function handler(req: FastifyRequest<{ Body: iBody }>, res: FastifyReply)
const session = req.session.get(`session`)!;
try {
const user = req.session.get(`user`)!;
const jerseys = await Jersey.find({
number: { $in: req.body.bids.map((j) => j.number) },
});

let jerseys: iJersey[];

try {
jerseys = logAndThrow(
await Promise.allSettled(
req.body.bids.map(async (j) => await Jersey.findOne({ number: j.number }).orFail().session(session.session)),
),
`Jersey parsing error`,
);
} catch (error) {
return await sendStatus(res, 400, `Invalid number(s).`);
}

if (!(await isEligible(user, jerseys, session))) {
return await sendStatus(res, 400, `Ineligible to bid requested numbers.`);
}

const currentRound = (await Server.findOne({ key: `jerseyBidRound` }).orFail().session(session.session))?.value;

const newBids = jerseys.map((jersey, index) => ({
user: user._id,
jersey: jersey._id,
priority: index,
round: currentRound,
}));

await Bid.deleteMany({ user: user._id }).session(session.session);
await Bid.create(newBids, { session: session.session });
await JerseyBid.deleteMany({ user: user._id }).session(session.session);
await JerseyBid.create(newBids, { session: session.session });

await logEvent(`USER PLACE BIDS`, session, JSON.stringify(newBids), user._id);

Expand All @@ -69,12 +84,12 @@ async function handler(req: FastifyRequest<{ Body: iBody }>, res: FastifyReply)
}
}

const create: RouteOptions<Server, IncomingMessage, ServerResponse, { Body: iBody }> = {
const bid: RouteOptions<HttpServer, IncomingMessage, ServerResponse, { Body: iBody }> = {
method: `POST`,
url: `/create`,
url: `/bid`,
schema,
preHandler: auth,
handler,
};

export { create };
export { bid };
Loading

0 comments on commit 76d7acf

Please sign in to comment.