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

Commit

Permalink
Merge pull request #250 from karrioapi/debub-multi-tenant
Browse files Browse the repository at this point in the history
(debug) multi-tenant setup
  • Loading branch information
danh91 committed Mar 8, 2023
2 parents 6d3a3da + 6a7b79e commit f7f5542
Show file tree
Hide file tree
Showing 5 changed files with 26 additions and 32 deletions.
5 changes: 4 additions & 1 deletion src/components/descriptions/shipment-preview.tsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ShipmentComponent } from '@/modules/Shipments/shipment';
import ConfirmModal from '@/components/confirm-modal';
import { useLocation } from '@/lib/helper';
import React, { useState } from 'react';

Expand Down Expand Up @@ -41,7 +42,9 @@ const ShipmentPreview: React.FC<ShipmentPreviewComponent> = ({ children }) => {
{(isActive && shipmentId) && <div className="modal-card is-medium-modal">
<section className="modal-card-body px-5 pt-0 pb-6">

<ShipmentComponent shipmentId={shipmentId} />
<ConfirmModal>
<ShipmentComponent shipmentId={shipmentId} />
</ConfirmModal>

</section>
</div>}
Expand Down
3 changes: 1 addition & 2 deletions src/lib/client.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,7 @@ function requestInterceptor(session?: SessionType) {
}

function setupRestClient(host: string, session?: SessionType): KarrioClient {
const url = host[host.length - 1] === '/' ? host.slice(0, -1) : host;
const client = new KarrioClient({ basePath: `${url || ''}` });
const client = new KarrioClient({ basePath: url$`${host || ''}` });

client.axios.interceptors.request.use(requestInterceptor(session));

Expand Down
33 changes: 8 additions & 25 deletions src/lib/data-fetching/index.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { UserContextDataType, Metadata, PortalSessionType, References, SessionType, SubscriptionType, OrgContextDataType, TenantType } from "@/lib/types";
import { UserContextDataType, Metadata, PortalSessionType, SessionType, SubscriptionType, OrgContextDataType, TenantType } from "@/lib/types";
import { GetServerSideProps, GetServerSidePropsContext, NextApiRequest, NextApiResponse } from "next";
import { createServerError, isNone, ServerErrorCode, url$ } from "@/lib/helper";
import { getSession } from "next-auth/react";
Expand All @@ -18,13 +18,12 @@ export const getServerSideProps: GetServerSideProps = async (ctx) => {
const pathname = ctx.resolvedUrl;

const orgId = ((session as any)?.orgId as string) || null;
const testMode = ((session as any)?.testMode as boolean);

const metadata = await loadAPIMetadata(ctx).catch(_ => _);
const data = await loadContextData(session, metadata.metadata);
const subscription = await checkSubscription(session, metadata.metadata);

await setSessionCookies(ctx, metadata.metadata, testMode, orgId);
await setSessionCookies(ctx, orgId);

if (needValidSubscription(subscription)) {
return {
Expand All @@ -49,7 +48,7 @@ export async function loadAPIMetadata(ctx: RequestContext): Promise<{ metadata?:
const { data: metadata } = await axios.get<Metadata>(API_URL);

// TODO:: implement version compatibility check here.
await setSessionCookies(ctx as any, metadata);
await setSessionCookies(ctx as any);
resolve({ metadata });
} catch (e: any | Response) {
logger.error(`Failed to fetch API metadata from (${API_URL})`);
Expand Down Expand Up @@ -110,21 +109,10 @@ export async function loadContextData(session: SessionType, metadata: Metadata):
}
}

export async function setSessionCookies(ctx: GetServerSidePropsContext, metadata?: Metadata, testMode?: boolean, orgId?: string | null) {
export async function setSessionCookies(ctx: GetServerSidePropsContext, orgId?: string | null) {
// Sets the authentication orgId cookie if the session has one
if (ctx.res && !!orgId) {
ctx.res.setHeader('Set-Cookie', `orgId=${orgId}`);
}
if (!!ctx.params?.site) {
ctx.res.setHeader('Set-Cookie', `appUrl=${ctx.params?.site}`);
}
if (!!metadata?.HOST) {
const host = publicRuntimeConfig?.MULTI_TENANT ? metadata.HOST : publicRuntimeConfig?.KARRIO_PUBLIC_URL
ctx.res.setHeader('Set-Cookie', `apiUrl=${host}`);
ctx.res.setHeader('Set-Cookie', `apiHOST=${metadata.HOST}`);
}
if (!!testMode) {
ctx.res.setHeader('Set-Cookie', `testMode=${testMode}`);
ctx.res.setHeader('Set-Cookie', `orgId=${orgId}; path=${ctx.resolvedUrl || '/'}`);
}
}

Expand Down Expand Up @@ -214,20 +202,16 @@ async function getAPIURL(ctx: RequestContext) {
}

const params = (ctx as GetServerSidePropsContext).params;
const cookies = (ctx.req as NextApiRequest).cookies;
const apiHost = cookies ? cookies['apiHOST'] : null;
const host = cookies ? cookies['HOST'] : null;
const headers = (ctx.req as NextApiRequest).headers;
const host = headers ? headers.host : null;
const site = params ? params.site : null;

if (!!site === false && !!apiHost === true) return apiHost;

const app_domain = (site || host) as string;
const tenant = (publicRuntimeConfig?.MULTI_TENANT && !!app_domain
? (await loadTenantInfo({ app_domain }))
: null
);
const APIURL = (
!!serverRuntimeConfig?.TENANT_ENV_KEY
const APIURL = (!!serverRuntimeConfig?.TENANT_ENV_KEY
? (tenant?.api_domains || []).find(d => d.includes(serverRuntimeConfig?.TENANT_ENV_KEY))
: (tenant?.api_domains || [])[0]
);
Expand All @@ -236,7 +220,6 @@ async function getAPIURL(ctx: RequestContext) {
}



const USER_DATA_QUERY = `{
user {
email
Expand Down
10 changes: 8 additions & 2 deletions src/lib/data-fetching/tracker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,24 +2,30 @@ import { loadAPIMetadata } from "@/lib/data-fetching";
import { KarrioClient } from "@karrio/rest";
import { KARRIO_API } from "@/lib/client";
import { GetServerSideProps } from "next";
import { url$ } from "@/lib/helper";
import logger from "@/lib/logger";


export const getServerSideProps: GetServerSideProps = async (ctx) => {
const { res, params } = ctx;
const id = params?.id as string;
const metadata = await loadAPIMetadata(ctx).catch(_ => _);
const client = new KarrioClient({ basePath: `${metadata.metadata?.HOST || KARRIO_API}` });
const client = new KarrioClient({ basePath: url$`${metadata.metadata?.HOST || KARRIO_API}` });

try {
// Retrieve tracker by id
const data = await client.trackers.retrieves({ idOrTrackingNumber: id })
.then(({ data }) => ({ tracker: JSON.parse(JSON.stringify(data)) }))
.catch(_ => ({ message: `No Tracker ID nor Tracking Number found for ${id}` }));
.catch(_ => {
console.log(_)
return ({ message: `No Tracker ID nor Tracking Number found for ${id}` });
});

res.setHeader('Cache-Control', 'public, s-maxage=10, stale-while-revalidate=59')

return { props: { id, ...metadata, ...data } };
} catch (e) {
logger.error(e, "Failed to retrieve tracking info");
return { props: { id, ...metadata, ...(e as {}) } };
}
};
7 changes: 5 additions & 2 deletions src/lib/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,8 +274,11 @@ export const parseJwt = (token: string): any => {
export function url$(strings: TemplateStringsArray, ...keys: any[]) {
const base = (keys || []).reduce((acc, key, i) => acc + strings[i] + key, '');
const template = `${base}${strings[strings.length - 1]}`;

return template.replace(/([^:])(\/\/+)/g, '$1/');

const _url = template.replace(/([^:])(\/\/+)/g, '$1/')
const url = _url[_url.length - 1] === '/' ? _url.slice(0, -1) : _url;

return url;
}

export function gqlstr(node: ReturnType<typeof gql>): string {
Expand Down

1 comment on commit f7f5542

@vercel
Copy link

@vercel vercel bot commented on f7f5542 Mar 11, 2023

Choose a reason for hiding this comment

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

Successfully deployed to the following URLs:

karrio-cloud – ./

karrio-cloud.vercel.app
karrio-cloud-karrio.vercel.app
karrio-cloud-git-main-karrio.vercel.app

Please sign in to comment.