Skip to content

Commit

Permalink
refacotrs
Browse files Browse the repository at this point in the history
  • Loading branch information
vuvincent committed Sep 26, 2023
1 parent 642b670 commit 95f4bb4
Show file tree
Hide file tree
Showing 12 changed files with 507 additions and 110 deletions.
1 change: 0 additions & 1 deletion apps/api-v2/scripts/create-user.mts

This file was deleted.

2 changes: 2 additions & 0 deletions apps/api-v2/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import buildTasksRouter from "./routers/tasks";
import buildStatsRouter from "./routers/stats";
import { loggerOptions } from "./logging";
import responseTime from "response-time";
import { errorHandler } from "./mws";

export const createApp = () => {
const app = express();
Expand All @@ -22,6 +23,7 @@ export const createApp = () => {
credentials: true, // accept cookies from clients
})
);
app.use(errorHandler);
app.use(cookieParser()); // parses the cookies because apparently express doesn't do this by default
app.use(express.json()); // parses the request body
const responseTimeMws = responseTime();
Expand Down
24 changes: 21 additions & 3 deletions apps/api-v2/src/mws.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export const authenticateJWTMiddleware = async (
);
}
} catch (err) {
console.error("Could not connect to Redis: " + err);
logger.error("Could not connect to Redis: " + err);
return res.status(500).send(
new SupernovaResponse({
error: "Internal Server Error",
Expand Down Expand Up @@ -106,13 +106,31 @@ export const validateRequestSchema =
);
}
// log the error because this is unknown
logger.error(error);
return res.status(500).json(
res.status(500).json(
new SupernovaResponse({
message: "Internal Server Error",
error:
"An error occurred while validating the request; this is on us, not you. Please try again later.",
})
);
next(error);
}
};

/**
* Generic error handler for the application.
* Expect to have handled error response before this middleware
* @param err
* @param req
* @param res
* @param next
*/
export function errorHandler(
err: Error,
req: Request,
res: Response,
next: NextFunction
) {
logger.error(err);
next();
}
92 changes: 41 additions & 51 deletions apps/api-v2/src/routers/tasks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ import {
export default function buildTasksRouter(): Router {
const router = Router();

router.get("/tasks", authenticateJWTMiddleware, async (req, res) => {
router.get("/tasks", authenticateJWTMiddleware, async (req, res, next) => {
try {
const authCtx = getAuthContext(req);
// get all tasks for the user
Expand Down Expand Up @@ -43,16 +43,14 @@ export default function buildTasksRouter(): Router {
data: tasks,
})
);
} catch (err) {
if (err instanceof Error) {
console.error(err);
return res.status(500).json(
new SupernovaResponse({
message: "Something went wrong. Please try again later.",
error: "Internal Server Error",
})
);
}
} catch (e) {
res.status(500).json(
new SupernovaResponse({
message: "Something went wrong. Please try again later.",
error: "Internal Server Error",
})
);
next(e);
}
});

Expand All @@ -61,7 +59,7 @@ export default function buildTasksRouter(): Router {
"/tasks",
authenticateJWTMiddleware,
validateRequestSchema(createTaskRequestSchema),
async (req, res) => {
async (req, res, next) => {
try {
const authCtx = getAuthContext(req);
const task = await prisma.task.create({
Expand All @@ -81,15 +79,13 @@ export default function buildTasksRouter(): Router {
})
);
} catch (e) {
if (e instanceof Error) {
console.error(e);
return res.status(500).json(
new SupernovaResponse({
message: "Something went wrong. Please try again later.",
error: "Internal Server Error",
})
);
}
res.status(500).json(
new SupernovaResponse({
message: "Something went wrong. Please try again later.",
error: "Internal Server Error",
})
);
next(e);
}
}
);
Expand All @@ -100,7 +96,7 @@ export default function buildTasksRouter(): Router {
"/tasks/:id",
authenticateJWTMiddleware,
validateRequestSchema(updateTaskRequestSchema),
async (req, res) => {
async (req, res, next) => {
try {
const authCtx = getAuthContext(req);
const task = await prisma.task.update({
Expand All @@ -123,15 +119,13 @@ export default function buildTasksRouter(): Router {
})
);
} catch (e) {
if (e instanceof Error) {
console.error(e);
return res.status(500).json(
new SupernovaResponse({
message: "Something went wrong. Please try again later.",
error: "Internal Server Error",
})
);
}
res.status(500).json(
new SupernovaResponse({
message: "Something went wrong. Please try again later.",
error: "Internal Server Error",
})
);
next(e);
}
}
);
Expand All @@ -141,7 +135,7 @@ export default function buildTasksRouter(): Router {
"/tasks/:id",
authenticateJWTMiddleware,
validateRequestSchema(deleteTaskRequestSchema),
async (req, res) => {
async (req, res, next) => {
try {
const authCtx = getAuthContext(req);
const task = await prisma.task.update({
Expand All @@ -160,15 +154,13 @@ export default function buildTasksRouter(): Router {
})
);
} catch (e) {
if (e instanceof Error) {
console.error(e);
return res.status(500).json(
new SupernovaResponse({
message: "Something went wrong. Please try again later.",
error: "Internal Server Error",
})
);
}
res.status(500).json(
new SupernovaResponse({
message: "Something went wrong. Please try again later.",
error: "Internal Server Error",
})
);
next(e);
}
}
);
Expand All @@ -178,7 +170,7 @@ export default function buildTasksRouter(): Router {
"/tasks/:id/toggle-complete",
authenticateJWTMiddleware,
validateRequestSchema(toggleCompleteTaskRequestSchema),
async (req, res) => {
async (req, res, next) => {
try {
const authCtx = getAuthContext(req);
// find the task
Expand Down Expand Up @@ -213,15 +205,13 @@ export default function buildTasksRouter(): Router {
})
);
} catch (e) {
if (e instanceof Error) {
console.error(e);
return res.status(500).json(
new SupernovaResponse({
message: "Something went wrong. Please try again later.",
error: "Internal Server Error",
})
);
}
res.status(500).json(
new SupernovaResponse({
message: "Something went wrong. Please try again later.",
error: "Internal Server Error",
})
);
next(e);
}
}
);
Expand Down
3 changes: 3 additions & 0 deletions apps/desktop-v2/.gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -33,3 +33,6 @@ yarn-error.log*
# typescript
*.tsbuildinfo
next-env.d.ts

# Sentry Auth Token
.sentryclirc
51 changes: 26 additions & 25 deletions apps/desktop-v2/hooks/useSupernovaTasksUI.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -79,8 +79,7 @@ export default function useSupernovaTasksUI() {
});
}
console.log("updated successfully");
} catch (e: any) {
console.error(e);
} catch (e) {
// TODO: show error toast
makeToast("Something went wrong", "error", {
description: `This is something on our side.`,
Expand Down Expand Up @@ -143,29 +142,31 @@ export default function useSupernovaTasksUI() {
};
// optimistically update the task in the frontend
setTasks(
tasks.map((task) => {
if (task.id === chosenTask.id) {
return {
...task,
title: newTask.title,
originalBuildText: newTask.originalBuildText,
description: newTask.description,
startTime:
updatePayload.startAt === null
? undefined
: updatePayload.startAt === undefined
? chosenTask.startTime
: newTask.startTime, // if it's null, then cleared, else if undefined then don't update
expectedDurationSeconds:
updatePayload.expectedDurationSeconds === null
? undefined
: updatePayload.expectedDurationSeconds === undefined
? chosenTask.expectedDurationSeconds
: newTask.expectedDurationSeconds, // if it's null, then cleared, else if undefined then don't update
};
}
return task;
})
reorderTaskList(
tasks.map((task) => {
if (task.id === chosenTask.id) {
return {
...task,
title: newTask.title,
originalBuildText: newTask.originalBuildText,
description: newTask.description,
startTime:
updatePayload.startAt === null
? undefined
: updatePayload.startAt === undefined
? chosenTask.startTime
: newTask.startTime, // if it's null, then cleared, else if undefined then don't update
expectedDurationSeconds:
updatePayload.expectedDurationSeconds === null
? undefined
: updatePayload.expectedDurationSeconds === undefined
? chosenTask.expectedDurationSeconds
: newTask.expectedDurationSeconds, // if it's null, then cleared, else if undefined then don't update
};
}
return task;
})
)
);
makeToast("Task updated successfully", "success");

Expand Down
36 changes: 35 additions & 1 deletion apps/desktop-v2/next.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,38 @@ const nextConfig = {
transpilePackages: ["@supernova/api-client"],
}

module.exports = nextConfig
// Injected content via Sentry wizard below

const { withSentryConfig } = require("@sentry/nextjs");

module.exports = withSentryConfig(
nextConfig,
{
// For all available options, see:
// https://github.com/getsentry/sentry-webpack-plugin#options

// Suppresses source map uploading logs during build
silent: true,
org: "supernova-0z",
project: "javascript-nextjs",
},
{
// For all available options, see:
// https://docs.sentry.io/platforms/javascript/guides/nextjs/manual-setup/

// Upload a larger set of source maps for prettier stack traces (increases build time)
widenClientFileUpload: true,

// Transpiles SDK to be compatible with IE11 (increases bundle size)
transpileClientSDK: true,

// Routes browser requests to Sentry through a Next.js rewrite to circumvent ad-blockers (increases server load)
tunnelRoute: "/monitoring",

// Hides source maps from generated client bundles
hideSourceMaps: true,

// Automatically tree-shake Sentry logger statements to reduce bundle size
disableLogger: true,
}
);
1 change: 1 addition & 0 deletions apps/desktop-v2/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
"@radix-ui/react-checkbox": "^1.0.4",
"@radix-ui/react-dialog": "^1.0.4",
"@radix-ui/react-icons": "^1.3.0",
"@sentry/nextjs": "^7.72.0",
"@supernova/api-client": "workspace:*",
"@supernova/types": "workspace:*",
"@tauri-apps/api": "^1.4.0",
Expand Down
30 changes: 30 additions & 0 deletions apps/desktop-v2/sentry.client.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// This file configures the initialization of Sentry on the client.
// The config you add here will be used whenever a users loads a page in their browser.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

import * as Sentry from "@sentry/nextjs";

Sentry.init({
dsn: "https://6f6f7fe2b894e163826396f63d7a2eec@o4505948505702400.ingest.sentry.io/4505948506816512",

// Adjust this value in production, or use tracesSampler for greater control
tracesSampleRate: 1,

// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,

replaysOnErrorSampleRate: 1.0,

// This sets the sample rate to be 10%. You may want this to be 100% while
// in development and sample at a lower rate in production
replaysSessionSampleRate: 0.1,

// You can remove this option if you're not planning to use the Sentry Session Replay feature:
integrations: [
new Sentry.Replay({
// Additional Replay configuration goes in here, for example:
maskAllText: true,
blockAllMedia: true,
}),
],
});
16 changes: 16 additions & 0 deletions apps/desktop-v2/sentry.edge.config.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// This file configures the initialization of Sentry for edge features (middleware, edge routes, and so on).
// The config you add here will be used whenever one of the edge features is loaded.
// Note that this config is unrelated to the Vercel Edge Runtime and is also required when running locally.
// https://docs.sentry.io/platforms/javascript/guides/nextjs/

import * as Sentry from "@sentry/nextjs";

Sentry.init({
dsn: "https://6f6f7fe2b894e163826396f63d7a2eec@o4505948505702400.ingest.sentry.io/4505948506816512",

// Adjust this value in production, or use tracesSampler for greater control
tracesSampleRate: 1,

// Setting this option to true will print useful information to the console while you're setting up Sentry.
debug: false,
});
Loading

0 comments on commit 95f4bb4

Please sign in to comment.