Skip to content

Commit

Permalink
feat: serve switchboard from subdirectories (#108)
Browse files Browse the repository at this point in the history
Co-authored-by: acaldas <[email protected]>
  • Loading branch information
froid1911 and acaldas authored Apr 4, 2024
1 parent 6dfcaa3 commit fbd6baa
Show file tree
Hide file tree
Showing 12 changed files with 88 additions and 52 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/build-and-deploy-powerhouse-staging.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ jobs:
dockerfile_directory: ./frontend
dockerfile_name: Dockerfile
process_type: web
docker_options: "--build-arg NEXT_PUBLIC_SWITCHBOARD_GRAPHQL_HOST=${{ secrets.NEXT_PUBLIC_SWITCHBOARD_GRAPHQL_HOST }}"
docker_options: "--build-arg NEXT_PUBLIC_SWITCHBOARD_GRAPHQL_HOST=${{ secrets.NEXT_PUBLIC_SWITCHBOARD_GRAPHQL_HOST }} --build-arg BASE_PATH=/makerdao/switchboard"
- name: Build, Push and Release NGINX to Heroku. # Your custom step name
uses: gonuit/[email protected]
with:
Expand Down
26 changes: 22 additions & 4 deletions api/src/app.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,9 +12,26 @@ import { nodeProfilingIntegration } from "@sentry/profiling-node";
const logger = getChildLogger({ msgPrefix: 'APP' });
const startupTime = new Date();

export const createApp = (): Express => {
export const createApp = (): { app: Express, router: express.Router } => {
logger.debug('Creating app');
const app = express();
const router = express.Router();

if (process.env.SENTRY_DSN) {
Sentry.init({
dsn: process.env.SENTRY_DSN,
integrations: [
nodeProfilingIntegration(),
new Sentry.Integrations.Express({
app,
}),
],
tracesSampleRate: 1.0,
});

app.use(Sentry.Handlers.requestHandler());
app.use(Sentry.Handlers.tracingHandler());
}

if (process.env.SENTRY_DSN) {
Sentry.init({
Expand Down Expand Up @@ -48,11 +65,12 @@ export const createApp = (): Express => {
});
});

app.get(
router.get(
'/explorer/:driveId?',
(req, res) => {
res.setHeader('Content-Type', 'text/html')
const endpoint = req.params.driveId !== undefined ? `/d/${req.params.driveId}` : '/drives'
const basePath = process.env.BASE_PATH === "/" ? "" : process.env.BASE_PATH || '';
const endpoint = `${basePath}${req.params.driveId !== undefined ? `/d/${req.params.driveId}` : '/drives'}`
res.send(renderPlaygroundPage({
endpoint: endpoint,
settings: {
Expand All @@ -62,5 +80,5 @@ export const createApp = (): Express => {
}
);

return app;
return { app, router };
};
11 changes: 8 additions & 3 deletions api/src/graphql/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,16 +45,17 @@ const createApolloDriveServer = (): ApolloServer<DriveContext> => new ApolloServ

export const startServer = async (
app: express.Application,
router: express.Router,
): Promise<Server> => {
logger.debug('Starting server');
const httpServer = createHttpServer(app);

const apolloIndex = createApolloIndexServer();
const apolloDrive = createApolloDriveServer();

await apolloIndex.start();
await apolloDrive.start();

app.use(
router.use(
'/drives',
cors<cors.CorsRequest>(),
cookierParser(undefined, { decode: (value: string) => value }),
Expand All @@ -64,7 +65,7 @@ export const startServer = async (
}),
);

app.use(
router.use(
'/d/:driveId',
cors<cors.CorsRequest>(),
cookierParser(undefined, { decode: (value: string) => value }),
Expand All @@ -74,10 +75,14 @@ export const startServer = async (
}),
);

const basePath = process.env.BASE_PATH || '/';
app.use(basePath, router);
app.use(errorHandler);
if (process.env.SENTRY_DSN) {
app.use(Sentry.Handlers.errorHandler());
}

const httpServer = createHttpServer(app);
return httpServer.listen({ port: PORT }, () => {
logger.info(`Running on ${PORT}`);
});
Expand Down
4 changes: 2 additions & 2 deletions api/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,10 @@ import { getChildLogger } from './logger';

const logger = getChildLogger({ msgPrefix: 'SERVER' });

const application = createApp();
const { app, router } = createApp();

/* istanbul ignore next @preserve */
startServer(application)
startServer(app, router)
.then((e) => {
// Hot Module Replacement
if (import.meta.hot) {
Expand Down
35 changes: 19 additions & 16 deletions api/src/modules/real-world-assets/listener.ts
Original file line number Diff line number Diff line change
Expand Up @@ -225,15 +225,15 @@ async function rebuildRwaPortfolio(driveId: string, documentId: string, state: R
})

// add fees
for (const fee of transaction.fees ?? []) {
await prisma.rWAGroupTransactionFee.create({
data: {
if (transaction.fees) {
await prisma.rWAGroupTransactionFee.createMany({
data: transaction.fees.map(fee => ({
...fee,
portfolioId: portfolioEntity.id,
groupTransactionId: transaction.id,
id: fee.id ?? undefined
}
})
}))
});
}

// add relationships for fees
Expand Down Expand Up @@ -713,16 +713,19 @@ const surgicalOperations: Record<string, (input: any, portfolio: RWAPortfolio, p

"ADD_FEES_TO_GROUP_TRANSACTION": async (input: AddFeesToGroupTransactionInput, portfolio: RWAPortfolio, prisma: Prisma.TransactionClient) => {
logger.debug({ msg: "Adding fee transactions to group transaction", input });
for (const fee of input.fees ?? []) {
prisma.rWAGroupTransactionFee.create({
data: {
...fee,
portfolioId: portfolio.id,
groupTransactionId: input.id ?? undefined,
id: fee.id ?? undefined
}
});
// add fees
if (!input.fees) {
return;
}

await prisma.rWAGroupTransactionFee.createMany({
data: input.fees.map(fee => ({
...fee,
portfolioId: portfolio.id,
groupTransactionId: input.id,
id: fee.id ?? undefined
}))
});
},
"EDIT_GROUP_TRANSACTION_FEES": async (input: EditGroupTransactionFeesInput, portfolio: RWAPortfolio, prisma: Prisma.TransactionClient) => {
logger.debug({ msg: "Editing fee transaction", input });
Expand All @@ -742,8 +745,8 @@ const surgicalOperations: Record<string, (input: any, portfolio: RWAPortfolio, p
data: {
...fee,
portfolioId: portfolio.id,
groupTransactionId: input.id ?? undefined,
id: fee.id ?? undefined
groupTransactionId: input.id,
id: fee.id
}
});
}
Expand Down
4 changes: 4 additions & 0 deletions frontend/Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ WORKDIR /opt/app
COPY . .
COPY --from=deps /opt/app/node_modules ./node_modules
RUN npm install -g pnpm
ARG BASE_PATH=""
ENV BASE_PATH=${BASE_PATH}
RUN pnpm build

# Production image, copy all the files and run next
Expand All @@ -26,6 +28,8 @@ FROM node:lts-alpine AS runner
ARG X_TAG
WORKDIR /opt/app
ENV NODE_ENV=production
ARG BASE_PATH=""
ENV BASE_PATH=${BASE_PATH}
EXPOSE 3000
COPY --from=builder /opt/app/next.config.mjs ./
COPY --from=builder /opt/app/public ./public
Expand Down
3 changes: 3 additions & 0 deletions frontend/next.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,10 @@ const nextConfig = {
NEXT_PUBLIC_SWITCHBOARD_GRAPHQL_HOST:
process.env.NEXT_PUBLIC_SWITCHBOARD_GRAPHQL_HOST ||
"https://ph-switchboard-nginx-prod-c84ebf8c6e3b.herokuapp.com",
NEXT_PUBLIC_BASE_PATH: process.env.BASE_PATH ?? "",
},
basePath: process.env.BASE_PATH ?? "/",
assetPrefix: process.env.BASE_PATH ?? "/",
};

export default nextConfig;
Binary file removed frontend/src/app/favicon.ico
Binary file not shown.
9 changes: 6 additions & 3 deletions frontend/src/app/layout.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -22,16 +22,19 @@ export default function RootLayout({
<link
rel="apple-touch-icon"
sizes="180x180"
href="/apple-touch-icon.png"
href={`${process.env.NEXT_PUBLIC_BASE_PATH}/apple-touch-icon.png`}
/>

<link
rel="icon"
type="image/png"
sizes="16x16"
href="/favicon-16x16.png"
href={`${process.env.NEXT_PUBLIC_BASE_PATH}/favicon-16x16.png`}
/>
<link
rel="manifest"
href={`${process.env.NEXT_PUBLIC_BASE_PATH}/site.webmanifest`}
/>
<link rel="manifest" href="/site.webmanifest" />
</head>
<body className={inter.className}>
<div className="bg-gray-100">
Expand Down
18 changes: 10 additions & 8 deletions frontend/src/components/header/header.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@ import { useRouter } from "next/navigation";
import { UserCircleIcon } from "@heroicons/react/24/solid";
import Link from "next/link";
import { useEffect, useState } from "react";

import logo from "../../../public/assets/logo.svg";
import github from "../../../public/assets/github.svg";
export default function Header() {
const address = authStore((state) => state.address);
const gqlToken = authStore((state) => state.gqlToken);
Expand Down Expand Up @@ -40,7 +41,13 @@ export default function Header() {
<div className="flex items-start">
<SwitchboardLink href="/">
<div className="flex flex-row items-center">
<img src="/assets/logo.svg" className="w-10" />
<Image
src={logo}
alt="Switchboard Logo"
className="w-10"
width="32"
height="32"
/>
Switchboard API
</div>
</SwitchboardLink>
Expand Down Expand Up @@ -87,12 +94,7 @@ export default function Header() {
href="https://github.com/powerhouse-inc/switchboard-boilerplate"
target="_blank"
>
<Image
src="/assets/github.svg"
alt="GitHub"
width="32"
height="32"
/>
<Image src={github} alt="GitHub" width="32" height="32" />
</Link>
</div>
</div>
Expand Down
3 changes: 2 additions & 1 deletion nginx/Dockerfile
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
FROM nginx:stable
ENV PORT=80

ENV BASE_PATH=""
ENV BACKEND=https://ph-switchboard-api-prod-2f0358a27fa5.herokuapp.com
ENV FRONTEND=https://ph-switchboard-frontend-prod-2030e418555a.herokuapp.com
ENV WUNDERGRAPH=https://ph-switchboard-wgraph-prod-46a95adab5b7.herokuapp.com

COPY nginx.conf /etc/nginx/conf.d/default.conf.template
CMD /bin/sh -c "envsubst '\$PORT,\$BACKEND,\$FRONTEND,\$WUNDERGRAPH' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'
CMD /bin/sh -c "envsubst '\$BASE_PATH,\$PORT,\$BACKEND,\$FRONTEND,\$WUNDERGRAPH' < /etc/nginx/conf.d/default.conf.template > /etc/nginx/conf.d/default.conf" && nginx -g 'daemon off;'

25 changes: 11 additions & 14 deletions nginx/nginx.conf
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,31 @@ server {
listen [::]:${PORT};
server_name localhost;

# frontend
location / {
rewrite /(.*) /$1 break;
proxy_pass ${FRONTEND};
}

# drives graphql endpoint
location /drives {
rewrite /drives/(.*) /drives/$1 break;
location ${BASE_PATH}/drives {
proxy_pass ${BACKEND};
}

# drive graphql endpoint
location /d {
rewrite /d/(.*) /d/$1 break;
location ${BASE_PATH}/d {
proxy_pass ${BACKEND};
}

# GraphQL Explorer
location /explorer {
rewrite /explorer/(.*) /explorer/$1 break;
location ${BASE_PATH}/explorer {
proxy_pass ${BACKEND};
}

# graphql API composition
location /wundergraph/graphql {
rewrite /wundergraph/graphql /graphql break;
location ${BASE_PATH}/wundergraph/graphql {
rewrite ${BASE_PATH}/wundergraph/graphql /graphql break;
proxy_pass ${WUNDERGRAPH};
}

# frontend
location / {
rewrite /(.*) /$1 break;
proxy_pass ${FRONTEND};
}
}

0 comments on commit fbd6baa

Please sign in to comment.