Skip to content

Commit

Permalink
[util] Try reading project ID/dataset from .env files
Browse files Browse the repository at this point in the history
  • Loading branch information
rexxars committed Dec 6, 2019
1 parent da11acf commit b554f9e
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 3 deletions.
1 change: 1 addition & 0 deletions packages/@sanity/util/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
},
"homepage": "https://www.sanity.io/",
"dependencies": {
"dotenv": "^8.2.0",
"fs-extra": "^6.0.1",
"get-random-values": "^1.2.0",
"lodash": "^4.17.15",
Expand Down
33 changes: 30 additions & 3 deletions packages/@sanity/util/src/reduceConfig.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
/* eslint-disable no-process-env */
import fs from 'fs'
import path from 'path'
import {mergeWith} from 'lodash'
import dotenv from 'dotenv'

const sanityEnv = process.env.SANITY_ENV || 'production'
const basePath = process.env.SANITY_STUDIO_BASEPATH || process.env.STUDIO_BASEPATH
Expand All @@ -8,9 +11,6 @@ const apiHosts = {
development: 'http://api.sanity.wtf'
}

const projectId = process.env.SANITY_STUDIO_PROJECT_ID || undefined
const dataset = process.env.SANITY_STUDIO_DATASET || undefined

const processEnvConfig = {
project: basePath ? {basePath} : {}
}
Expand All @@ -28,7 +28,34 @@ function merge(objValue, srcValue, key) {
return undefined
}

function tryReadDotEnv(studioRootPath) {
const configEnv = process.env.NODE_ENV || 'development'
const envFile = path.join(studioRootPath, `.env.${configEnv}`)
let parsed = {}
try {
// eslint-disable-next-line no-sync
parsed = dotenv.parse(fs.readFileSync(envFile, {encoding: 'utf8'}))
} catch (err) {
if (err.code !== 'ENOENT') {
// eslint-disable-next-line no-console
console.error(`There was a problem processing the .env file (${envFile})`, err)
}
}

return parsed
}

export default (rawConfig, env = 'development', options: {studioRootPath?: string} = {}) => {
const studioRootPath = options.studioRootPath

let envVars = {...process.env}
if (studioRootPath) {
envVars = {...envVars, ...tryReadDotEnv(studioRootPath)}
}

const projectId = envVars.SANITY_STUDIO_PROJECT_ID
const dataset = envVars.SANITY_STUDIO_DATASET

const apiHost = apiHosts[sanityEnv]
const api = clean({apiHost, projectId, dataset})
const sanityConf = {api}
Expand Down

0 comments on commit b554f9e

Please sign in to comment.