Skip to content
This repository has been archived by the owner on Mar 12, 2024. It is now read-only.

Commit

Permalink
Feature/api in app router (#237)
Browse files Browse the repository at this point in the history
* Create param validator

* Move discord

* Move user settings getter to app router

* Use standard var

* move getAllPublicUserData to app router

* Better error handling

* Delete getAllData.ts

* Delete discord

* Throw errors

* Handle error throwing

* Move updateSettings to app router

* Update confluence.svg

* Add present params return

* Fix token getter

* Fix token getter
  • Loading branch information
EstebanDalelR authored Aug 11, 2023
1 parent a5d0da1 commit 3fe55bd
Show file tree
Hide file tree
Showing 15 changed files with 160 additions and 103 deletions.
22 changes: 22 additions & 0 deletions app/api/user/getAllPublicUserData/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import validateParams from "../../../../utils/api/validateParams";
import getAllPublicUserData from "../../../../utils/db/user/getAllPublicUserData";

export async function POST(request: Request) {
const req = await request.json();
const { missingParams } = validateParams(req, ["email"]);

if (missingParams.length > 0) {
return NextResponse.json({
error: `Missing parameters: ${missingParams.join(", ")}`,
});
}

try {
let dbResponse = await getAllPublicUserData({ email: req.email });
return NextResponse.json(dbResponse);
} catch (err) {
console.error("Error fetching db data:", err);
return NextResponse.json({ error: "Failed to fetch db data." });
}
}
22 changes: 22 additions & 0 deletions app/api/user/settings/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
import { NextResponse } from "next/server";
import getUserSettings from "../../../../utils/db/user/settings";
import validateParams from "../../../../utils/api/validateParams";

export async function POST(request: Request) {
const req = await request.json();
const { missingParams } = validateParams(req, ["email"]);

if (missingParams.length > 0) {
return NextResponse.json({
error: `Missing parameters: ${missingParams.join(", ")}`,
});
}

try {
let dbResponse = await getUserSettings({ email: req.email });
return NextResponse.json(dbResponse);
} catch (err) {
console.error("Error fetching db data:", err);
return NextResponse.json({ error: "Failed to fetch db data." });
}
}
25 changes: 25 additions & 0 deletions app/api/user/updateSettings/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { NextResponse } from "next/server";
import validateParams from "../../../../utils/api/validateParams";
import patchUserSettings from "../../../../utils/db/user/patchUserSettings";

export async function POST(request: Request) {
const req = await request.json();
const { missingParams } = validateParams(req, ["email", "userSettings"]);

if (missingParams.length > 0) {
return NextResponse.json({
error: `Missing parameters: ${missingParams.join(", ")}`,
});
}

try {
let dbResponse = await patchUserSettings({
email: req.email,
userSettings: req.userSettings,
});
return NextResponse.json(dbResponse);
} catch (err) {
console.error("Error fetching db data:", err);
return NextResponse.json({ error: "Failed to fetch db data." });
}
}
10 changes: 0 additions & 10 deletions pages/api/discord/getUser.ts

This file was deleted.

35 changes: 17 additions & 18 deletions pages/api/extension/getContext.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Octokit } from "octokit";
import { trackEvent } from "../../../utils/analytics/azureAppInsights";
import getAllData from "../../../utils/db/user/getAllData";
import getUserTokens from "../../../utils/db/user/getUserTokens";
import updateTokensFromJira from "../../../utils/jira/updateTokens";
import updateTokens from "../../../utils/db/jira/updateTokens";
import searchMessageByText from "../../../utils/slack/searchMessageByText";
Expand All @@ -9,10 +9,10 @@ function replaceSpecialChars(inputString) {
return inputString.toLowerCase().replace(specialChars, " ");
}

async function fetchGitHubIssues(userTokens, owner, repo) {
const parsedGithubData = JSON.parse(userTokens.github_data);
async function fetchGitHubIssues(parsedUserTokens, owner, repo) {
const { github_token } = parsedUserTokens;
const octokit = new Octokit({
auth: parsedGithubData.access_token,
auth: github_token,
});

let q = `repo:${owner}/${repo}`;
Expand Down Expand Up @@ -49,26 +49,26 @@ async function fetchGitHubIssues(userTokens, owner, repo) {
}
return issues?.data?.items;
}
async function fetchJiraTickets(userTokens, PRTitles) {
const parsedJiraData = JSON.parse(userTokens.jira_data);
async function fetchJiraTickets(parsedUserTokens, PRTitles) {
const { jira_token, jira_refresh_token, cloudId, user } = parsedUserTokens;

if (!parsedJiraData.access_token || !parsedJiraData.refresh_token) {
if (!jira_token || !jira_refresh_token) {
return { error: "no jira token" };
} else {
const newAccessTokens = await updateTokensFromJira({
refresh_token: parsedJiraData.refresh_token,
refresh_token: jira_refresh_token,
});
if (!newAccessTokens?.access_token) {
return { error: "no access_token" };
}

if (!parsedJiraData.cloudId) {
if (!cloudId) {
return { error: "no Jira cloudId" };
}
await updateTokens({
access_token: newAccessTokens.access_token,
refresh_token: newAccessTokens.refresh_token,
user: userTokens.user,
user: user,
});

let cleanPRTitles = Array.from(
Expand All @@ -84,7 +84,7 @@ async function fetchJiraTickets(userTokens, PRTitles) {
.join(" OR ");
let jql = `(${summaryQuery}) AND (${descriptionQuery}) ORDER BY created DESC`;
let returnVal = await fetch(
`https://api.atlassian.com/ex/jira/${parsedJiraData.cloudId}/rest/api/3/search`,
`https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/search`,
{
method: "POST",
headers: {
Expand All @@ -105,7 +105,7 @@ async function fetchJiraTickets(userTokens, PRTitles) {
});
const serverPromise = async () => {
const serverInfo = await fetch(
`https://api.atlassian.com/ex/jira/${parsedJiraData.cloudId}/rest/api/3/serverInfo`,
`https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/serverInfo`,
{
method: "GET",
headers: {
Expand Down Expand Up @@ -133,24 +133,23 @@ async function fetchJiraTickets(userTokens, PRTitles) {
return returnVal?.slice(0, 3);
}
}
async function fetchSlackConversations(userTokens, PRTitles) {
let parsedSlackData = JSON.parse(userTokens.slack_data);
async function fetchSlackConversations(parsedUserTokens, PRTitles) {
let { slack_token } = parsedUserTokens;
let slackValue = {};

if (!parsedSlackData.user_token) {
if (!slack_token) {
slackValue = { error: "no slack token" };
} else {
let response = await searchMessageByText({
text: `${PRTitles.join(" ")}`,
user_token: parsedSlackData.user_token,
user_token: slack_token,
});
slackValue = response?.messages?.matches?.slice(0, 3);
}
return slackValue;
}
export default async function handler(req, res) {
const { user, gitSystem, repo, owner, commitList } = req.body;

trackEvent({
name: "extensionContext",
properties: { user, repo, owner, gitSystem },
Expand All @@ -173,7 +172,7 @@ export default async function handler(req, res) {
}
let userTokens;
try {
userTokens = await getAllData(user);
userTokens = await getUserTokens({ email: user });
} catch (error) {
console.error(
"An error occurred while getting user tokens:",
Expand Down
25 changes: 13 additions & 12 deletions pages/api/hover/getHoverData.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import getAllData from "../../../utils/db/user/getAllData";
import getUserTokens from "../../../utils/db/user/getUserTokens";
import { Octokit } from "octokit";
import { trackEvent } from "../../../utils/analytics/azureAppInsights";
import updateTokensFromJira from "../../../utils/jira/updateTokens";
Expand Down Expand Up @@ -33,7 +33,7 @@ export default async function handler(req, res) {

let userTokens;
try {
userTokens = await getAllData(user);
userTokens = await getUserTokens({ email: user });
} catch (error) {
console.error(
"An error occurred while getting user tokens:",
Expand All @@ -42,9 +42,10 @@ export default async function handler(req, res) {
return res.send({ error });
}
async function fetchGitHubIssues(userTokens, owner, repo) {
const parsedGithubData = JSON.parse(userTokens.github_data);
const { github_token } = userTokens;

const octokit = new Octokit({
auth: parsedGithubData.access_token,
auth: github_token,
});

let q = `repo:${owner}/${repo}`;
Expand All @@ -64,18 +65,18 @@ export default async function handler(req, res) {
return issues?.data?.items;
}
async function fetchJiraTickets(userTokens, commitTitle) {
const parsedJiraData = JSON.parse(userTokens.jira_data);
if (!parsedJiraData.access_token || !parsedJiraData.refresh_token) {
const { jira_token, jira_refresh_token, cloudId, user } = userTokens;
if (!jira_token || !jira_refresh_token) {
return { error: "no jira token" };
} else {
const newAccessTokens = await updateTokensFromJira({
refresh_token: parsedJiraData.refresh_token,
refresh_token: jira_refresh_token,
});
if (!newAccessTokens?.access_token) {
return { error: "no access_token" };
}

if (!parsedJiraData.cloudId) {
if (!cloudId) {
return { error: "no Jira cloudId" };
}
await updateTokens({
Expand All @@ -86,7 +87,7 @@ export default async function handler(req, res) {

let jql = `(summary ~ "${commitTitle}") AND (description ~ "${commitTitle}") ORDER BY created DESC`;
let returnVal = await fetch(
`https://api.atlassian.com/ex/jira/${parsedJiraData.cloudId}/rest/api/3/search`,
`https://api.atlassian.com/ex/jira/${cloudId}/rest/api/3/search`,
{
method: "POST",
headers: {
Expand All @@ -111,15 +112,15 @@ export default async function handler(req, res) {
}
}
async function fetchSlackConversations(userTokens, commitTitle) {
let parsedSlackData = JSON.parse(userTokens.slack_data);
let { slack_token } = userTokens;
let slackValue = {};

if (!parsedSlackData.user_token) {
if (!slack_token) {
slackValue = { error: "no slack token" };
} else {
let response = await searchMessageByText({
text: commitTitle,
user_token: parsedSlackData.user_token,
user_token: slack_token,
count: 1,
});
slackValue = response?.messages?.matches;
Expand Down
10 changes: 0 additions & 10 deletions pages/api/user/getAllPublicUserData.ts

This file was deleted.

10 changes: 0 additions & 10 deletions pages/api/user/settings.ts

This file was deleted.

14 changes: 0 additions & 14 deletions pages/api/user/updateSettings.ts

This file was deleted.

36 changes: 22 additions & 14 deletions public/logos/confluence.svg
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
23 changes: 23 additions & 0 deletions utils/api/validateParams.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
interface ValidationResult {
missingParams: string[];
presentParams: string[];
requiredParams: string[];
}

export default function validateParams(
body: any,
requiredParams: string[]
): ValidationResult {
let missingParams: string[] = [];
let presentParams: string[] = [];

for (let paramName of requiredParams) {
if (body[paramName]) {
presentParams.push(paramName);
} else {
missingParams.push(paramName);
}
}

return { missingParams, presentParams, requiredParams };
}
7 changes: 4 additions & 3 deletions utils/db/user/getAllPublicUserData.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import "server-only";
import executeRequest from "../azuredb";

export default async function getAllPublicUserData(user): Promise<any> {
export default async function getAllPublicUserData({ email }): Promise<any> {
try {
let data = await executeRequest(
`EXEC dbo.get_user_all_public_data @watermelon_user = '${user}'`
`EXEC dbo.get_user_all_public_data @watermelon_user = '${email}'`
);
return data;
} catch (err) {
console.error(err);
return err;
throw err;
}
}
Loading

1 comment on commit 3fe55bd

@vercel
Copy link

@vercel vercel bot commented on 3fe55bd Aug 11, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.