Skip to content

Commit

Permalink
start api directory, src/index.ts fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
dvargas92495 committed Jul 15, 2023
1 parent 42b37ad commit 2e4039a
Show file tree
Hide file tree
Showing 2 changed files with 217 additions and 28 deletions.
191 changes: 191 additions & 0 deletions api/website-status/get.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,191 @@
import { APIGatewayProxyHandler } from "aws-lambda";
import AWS from "aws-sdk";
import { dynamo, getActionGraph } from "../../lambdas/common/common";
import headers from "roamjs-components/backend/headers";
import getRoamJSUser from "roamjs-components/backend/getRoamJSUser";
import putRoamJSUser from "roamjs-components/backend/putRoamJSUser";

const getProgressProps = (
items: AWS.DynamoDB.ItemList = [],
deployItems: AWS.DynamoDB.ItemList = []
) => {
if (!items) {
return { progress: 0, progressType: "LAUNCHING" };
}
const launchIndex =
items.findIndex((s) => s.status.S === "INITIALIZING") + 1 ||
Number.MAX_VALUE;
const updateIndex =
items.findIndex((s) => s.status.S === "UPDATING") + 1 || Number.MAX_VALUE;
const shutdownIndex =
items.findIndex((s) => s.status.S === "SHUTTING DOWN") + 1 ||
Number.MAX_VALUE;
const minIndex = Math.min(launchIndex, updateIndex, shutdownIndex);
if (launchIndex === minIndex) {
const deployIndex = deployItems.findIndex((s) =>
["SUCCESS", "FAILURE"].includes(s.status.S || "")
);
if (deployIndex) {
return { progress: deployIndex / 5, progressType: "DEPLOYING" };
}
return { progress: launchIndex / 26, progressType: "LAUNCHING" };
} else if (updateIndex === minIndex) {
return { progress: updateIndex / 20, progressType: "UPDATING" };
} else {
return { progress: shutdownIndex / 18, progressType: "SHUTTING DOWN" };
}
};

export const handler: APIGatewayProxyHandler = (event) => {
const token =
event.headers.Authorization || event.headers.authorization || "";
return getRoamJSUser({ token, extensionId: "" })
.then((u) => [
{ ...u, token },
{
...event.queryStringParameters,
...JSON.parse(event.body || "{}"),
},
])
.then(async ([user, { graph }]) => {
const authUser = await getRoamJSUser({
token: user.token,
})
.then((u) => ({
email: u.email,
websiteGraph: u.websiteGraph as string,
authenticated: true,
error: undefined,
}))
.catch((e) =>
dynamo
.query({
TableName: "RoamJSWebsiteStatuses",
IndexName: "status-index",
ExpressionAttributeNames: {
"#s": "status",
"#a": "action_graph",
},
ExpressionAttributeValues: {
":s": { S: "DEPLOY" },
":a": { S: `sharing_${graph}` },
},
KeyConditionExpression: "#a = :a AND #s = :s",
})
.promise()
.then((r) =>
(r.Items || []).some((i) => i?.status_props?.S === user.email)
)
.then((authenticated) => ({
websiteGraph: graph,
authenticated,
email: "",
error: e,
}))
);
if (!authUser.authenticated) {
return {
statusCode: 403,
body: `User not authorized to get status of website from graph ${graph}. (${authUser.error})`,
headers,
};
}
if (!authUser.websiteGraph) {
return {
statusCode: 204,
body: JSON.stringify({authUser}),
headers,
};
}

if (
graph !== authUser.websiteGraph &&
!authUser.email.endsWith("@roamjs.com")
) {
return {
statusCode: 403,
body: "This user has a deployed website in another graph.",
headers,
};
}

const statuses = await dynamo
.query({
TableName: "RoamJSWebsiteStatuses",
KeyConditionExpression: "action_graph = :a",
ExpressionAttributeValues: {
":a": {
S: getActionGraph(graph as string),
},
},
Limit: 100,
ScanIndexForward: false,
IndexName: "primary-index",
})
.promise()
.catch((e) => {
console.error(e);
return { Items: [] };
});
if (!statuses.Items?.length) {
return {
statusCode: 204,
body: JSON.stringify({}),
headers,
};
}

const deployStatuses = await dynamo
.query({
TableName: "RoamJSWebsiteStatuses",
KeyConditionExpression: "action_graph = :a",
ExpressionAttributeValues: {
":a": {
S: getActionGraph(graph, "deploy"),
},
},
ScanIndexForward: false,
IndexName: "primary-index",
})
.promise();

const successDeployStatuses = (deployStatuses.Items || []).filter((s) =>
["SUCCESS", "FAILURE"].includes(s.status.S || "")
);
const first = deployStatuses.Items?.[0];
const deploys =
successDeployStatuses[0] === first
? successDeployStatuses
: first
? [first, ...successDeployStatuses]
: [];
const status = statuses.Items
? statuses.Items[0].status.S
: "INITIALIZING";
if (status === "INACTIVE")
await putRoamJSUser({
token: user.token,
data: {
websiteGraph: undefined,
},
});

return {
statusCode: 200,
body: JSON.stringify({
graph,
status,
statusProps: statuses.Items
? statuses.Items[0].status_props?.S
: "{}",
deploys: deploys.slice(0, 10).map((d) => ({
date: d.date.S,
status: d.status.S,
uuid: d.uuid.S,
})),
...getProgressProps(statuses.Items, deployStatuses.Items),
}),
headers,
};
});
};
54 changes: 26 additions & 28 deletions src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Dashboard, { getDeployBody } from "./components/StaticSiteDashboard";
import { runService } from "roamjs-components/components/ServiceComponents";
import { runService } from "./components/ServiceComponents";
import addStyle from "roamjs-components/dom/addStyle";
import runExtension from "roamjs-components/util/runExtension";
import apiPost from "roamjs-components/util/apiPost";
Expand All @@ -9,9 +9,8 @@ import registerSmartBlocksCommand from "roamjs-components/util/registerSmartBloc

const ID = "static-site";

export default runExtension({
run: () => {
const style = addStyle(`.bp3-tab-panel {
export default runExtension(async () => {
const style = addStyle(`.bp3-tab-panel {
width: 100%;
}
Expand All @@ -32,28 +31,27 @@ export default runExtension({
width: 8px;
}`);

runService({
id: ID,
Dashboard,
});

const deploy = () =>
apiPost(
"deploy-website",
getDeployBody(getPageUidByPageTitle(toConfigPageName(ID)))
);

window.roamjs.extension.staticSite = {
deploy,
};

registerSmartBlocksCommand({
text: "DEPLOYSITE",
handler: () => () =>
deploy()
.then(() => "Successfully deployed website!")
.catch((e) => "Error generating the report: " + e.message),
});
return { elements: [style] };
},
runService({
id: ID,
Dashboard,
});

const deploy = () =>
apiPost(
"deploy-website",
getDeployBody(getPageUidByPageTitle(toConfigPageName(ID)))
);

window.roamjs.extension.staticSite = {
deploy,
};

registerSmartBlocksCommand({
text: "DEPLOYSITE",
handler: () => () =>
deploy()
.then(() => "Successfully deployed website!")
.catch((e) => "Error generating the report: " + e.message),
});
return { elements: [style] };
});

0 comments on commit 2e4039a

Please sign in to comment.