Skip to content

Commit

Permalink
feat: environment variable shared utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
field123 committed Sep 29, 2023
1 parent 0f9e656 commit c7dcbce
Show file tree
Hide file tree
Showing 3 changed files with 89 additions and 106 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ import {
doesIndexExist,
} from "./utility/algolia/algolia"
import { logging } from "@angular-devkit/core"
import { attemptToAddEnvVariables } from "../../../lib/devkit/add-env-variables"

export function createAlgoliaIntegrationCommand(
ctx: CommandContext,
Expand Down Expand Up @@ -295,6 +296,17 @@ export function createAlgoliaIntegrationCommandHandler(
catalog.id.split("-")[0]
}`

const envVarResult = await attemptToAddEnvVariables(ctx, spinner, {
NEXT_PUBLIC_ALGOLIA_INDEX_NAME: algoliaIndexName,
})

if (!envVarResult.success) {
return {
success: false,
error: envVarResult.error,
}
}

logger.info(
boxen(
`Published catalog should have an Algolia index of ${colors.bold.green(
Expand All @@ -307,13 +319,6 @@ export function createAlgoliaIntegrationCommandHandler(
),
)

// TODO: tell the user the name of the published indexes so they can add them to their .env.local file
// - need to wait for the users integration publish job to be finished.
// - indexes are made up of the <catalog-name>_<first-section-uuid> e.g. Default_11ce355f
// - example with space in name "Default Catalog" -> Default_Catalog_11ce355f
// - check if the user has an .env.local file in the directory they have executed the command from
// - better yet prompt the user to ask if they want that done for them.

spinner.start(`Checking Algolia index exists...`)
while (true) {
const indexCheckResult = await doesIndexExist({
Expand All @@ -328,17 +333,6 @@ export function createAlgoliaIntegrationCommandHandler(
await timer(3000)
}

// if (!indexCheckResult) {
// spinner.fail(`Failed to check Algolia index`)
// return {
// success: false,
// error: {
// code: "FAILED_TO_CHECK_ALGOLIA_INDEX",
// message: "Failed to check Algolia index",
// }
// }
// }

spinner.text = `Found index ${algoliaIndexName} performing additional setup...`

const additionalAlgoliaSetupResult = await additionalAlgoliaSetup({
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,15 +25,8 @@ import {
EPPaymentsSetup,
epPaymentsSetupSchema,
} from "./util/setup-ep-payments-schema"
import {
callRule,
HostTree,
SchematicContext,
} from "@angular-devkit/schematics"
import { processUnknownError } from "../../../util/process-unknown-error"
import { Result } from "../../../types/results"
import { addEnvVariables } from "../../../lib/devkit/add-env-variables"
import { commitTree, createScopedHost } from "../../../lib/devkit/tree-util"
import { attemptToAddEnvVariables } from "../../../lib/devkit/add-env-variables"
import { checkGateway } from "@elasticpath/composable-common"

export function createEPPaymentsCommand(
Expand Down Expand Up @@ -160,8 +153,8 @@ export function createEPPaymentsCommandHandler(
}

await attemptToAddEnvVariables(ctx, spinner, {
accountId: options.accountId,
publishableKey: options.publishableKey,
NEXT_PUBLIC_STRIPE_ACCOUNT_ID: options.accountId,
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY: options.publishableKey,
})

spinner.succeed(`EP Payments setup successfully.`)
Expand All @@ -187,83 +180,6 @@ export function createEPPaymentsCommandHandler(
}
}

async function attemptToAddEnvVariables(
ctx: CommandContext,
spinner: ora.Ora,
{ accountId, publishableKey }: EpPaymentEnvVariableRecord,
): Promise<Result<{}, { code: string; message: string }>> {
const { workspaceRoot, composableRc } = ctx

if (!composableRc) {
return {
success: false,
error: {
code: "NO_COMPOSABLE_RC",
message: "Could not detect workspace root - missing composable.rc file",
},
}
}

spinner.start(
`Adding EP Payments environment variables to .env.local file...`,
)

if (!workspaceRoot) {
spinner.fail(
`Failed to add environment variables to .env.local file - missing workspace root`,
)
return {
success: false,
error: {
code: "EP",
message:
"Setup of EP Payment gateway succeeded but failed to add env variables to .env.local file",
},
}
}

await addEpPaymentEnvVariables(workspaceRoot, {
accountId,
publishableKey,
})

spinner.succeed(`Added EP Payments environment variables to .env.local file.`)

return {
success: true,
data: {},
}
}

type EpPaymentEnvVariableRecord = { accountId: string; publishableKey: string }

async function addEpPaymentEnvVariables(
workspaceRoot: string,
{ accountId, publishableKey }: EpPaymentEnvVariableRecord,
): Promise<void> {
const host = createScopedHost(workspaceRoot)

const initialTree = new HostTree(host)

if (!initialTree.exists(".env.local")) {
initialTree.create(".env.local", "")
}

const context = {} as unknown as SchematicContext

const rule = addEnvVariables(
{
NEXT_PUBLIC_STRIPE_ACCOUNT_ID: accountId,
NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY: publishableKey,
},
".env.local",
)

const tree = await callRule(rule, initialTree, context).toPromise()

await commitTree(host, tree)
}

async function resolveOptions(
args: EPPaymentsCommandArguments,
logger: logging.Logger,
Expand Down
75 changes: 74 additions & 1 deletion packages/composable-cli/src/lib/devkit/add-env-variables.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,36 @@
import { Rule, Tree } from "@angular-devkit/schematics"
import {
callRule,
HostTree,
Rule,
SchematicContext,
Tree,
} from "@angular-devkit/schematics"
import { commitTree, createScopedHost } from "./tree-util"
import { CommandContext } from "../../types/command"
import ora from "ora"
import { Result } from "../../types/results"

export async function addToEnvFile(
workspaceRoot: string,
filepath: string,
variables: Record<string, string>,
): Promise<void> {
const host = createScopedHost(workspaceRoot)

const initialTree = new HostTree(host)

if (!initialTree.exists(filepath)) {
initialTree.create(filepath, "")
}

const context = {} as unknown as SchematicContext

const rule = addEnvVariables(variables, filepath)

const tree = await callRule(rule, initialTree, context).toPromise()

await commitTree(host, tree)
}

export function addEnvVariables(
envVars: Record<string, string>,
Expand Down Expand Up @@ -41,3 +73,44 @@ export function parseEnv(src: string): EnvData {
}
return result
}

export async function attemptToAddEnvVariables(
ctx: CommandContext,
spinner: ora.Ora,
variables: Record<string, string>,
): Promise<Result<{}, { code: string; message: string }>> {
const { workspaceRoot, composableRc } = ctx

if (!composableRc) {
return {
success: false,
error: {
code: "NO_COMPOSABLE_RC",
message: "Could not detect workspace root - missing composable.rc file",
},
}
}

spinner.start(`Adding environment variables to .env.local file...`)

if (!workspaceRoot) {
spinner.fail(
`Failed to add environment variables to .env.local file - missing workspace root`,
)
return {
success: false,
error: {
code: "FAILED_TO_ADD_ENV_VARS",
message: "Failed to add env variables to .env.local file",
},
}
}
await addToEnvFile(workspaceRoot, ".env.local", variables)

spinner.succeed(`Added environment variables to .env.local file.`)

return {
success: true,
data: {},
}
}

0 comments on commit c7dcbce

Please sign in to comment.