Skip to content

Commit

Permalink
feat: update schema types formatting and init to include src (#7094)
Browse files Browse the repository at this point in the history
* feat: update schema types formatting and init to include src

* fix: update filenames and paths

* fix: change urlFor source type

* remove useCdn export
  • Loading branch information
SimeonGriggs authored Jul 15, 2024
1 parent 6fad0c5 commit d42da14
Show file tree
Hide file tree
Showing 3 changed files with 64 additions and 89 deletions.
30 changes: 20 additions & 10 deletions packages/@sanity/cli/src/actions/init-project/initProject.ts
Original file line number Diff line number Diff line change
Expand Up @@ -329,14 +329,16 @@ export default async function initSanity(
const fileExtension = useTypeScript ? 'ts' : 'js'

const embeddedStudio = unattended ? true : await promptForEmbeddedStudio(prompt)
let hasSrcFolder = false

if (embeddedStudio) {
// find source path (app or src/app)
const srcDir = 'app'
let srcPath = path.join(workDir, srcDir)
const appDir = 'app'
let srcPath = path.join(workDir, appDir)

if (!existsSync(srcPath)) {
srcPath = path.join(workDir, 'src', srcDir)
srcPath = path.join(workDir, 'src', appDir)
hasSrcFolder = true
if (!existsSync(srcPath)) {
await fs
.mkdir(srcPath, {recursive: true})
Expand Down Expand Up @@ -369,7 +371,7 @@ export default async function initSanity(
const sanityConfigPath = path.join(workDir, `sanity.config.${fileExtension}`)
await writeOrOverwrite(
sanityConfigPath,
sanityConfigTemplate
sanityConfigTemplate(hasSrcFolder)
.replace(':route:', embeddedStudioRouteFilePath.slice(workDir.length).replace('src/', ''))
.replace(':basePath:', studioPath),
)
Expand All @@ -382,18 +384,27 @@ export default async function initSanity(
const writeSourceFiles = async (
files: Record<string, string | Record<string, string>>,
folderPath?: string,
srcFolderPrefix?: boolean,
) => {
for (const [filePath, content] of Object.entries(files)) {
// check if file ends with full stop to indicate it's file and not directory (this only works with our template tree structure)
if (filePath.includes('.') && typeof content === 'string') {
await writeOrOverwrite(
path.join(workDir, 'sanity', folderPath || '', `${filePath}${fileExtension}`),
path.join(
workDir,
srcFolderPrefix ? 'src' : '',
'sanity',
folderPath || '',
`${filePath}${fileExtension}`,
),
content,
)
} else {
await fs.mkdir(path.join(workDir, 'sanity', filePath), {recursive: true})
await fs.mkdir(path.join(workDir, srcFolderPrefix ? 'src' : '', 'sanity', filePath), {
recursive: true,
})
if (typeof content === 'object') {
await writeSourceFiles(content, filePath)
await writeSourceFiles(content, filePath, srcFolderPrefix)
}
}
}
Expand All @@ -402,7 +413,7 @@ export default async function initSanity(
// ask what kind of schema setup the user wants
const templateToUse = unattended ? 'clean' : await promptForNextTemplate(prompt)

await writeSourceFiles(sanityFolder(useTypeScript, templateToUse))
await writeSourceFiles(sanityFolder(useTypeScript, templateToUse), undefined, hasSrcFolder)

// set tsconfig.json target to ES2017
const tsConfigPath = path.join(workDir, 'tsconfig.json')
Expand Down Expand Up @@ -459,8 +470,7 @@ export default async function initSanity(
`\n${chalk.green('Success!')} Your Sanity configuration files has been added to this project`,
)

// eslint-disable-next-line no-process-exit
process.exit(0)
return
}

// eslint-disable-next-line @typescript-eslint/no-shadow
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {blogSchemaFolder, blogSchemaJS, blogSchemaTS} from './schemaTypes/blog'

export const sanityConfigTemplate = `'use client'
export const sanityConfigTemplate = (hasSrcFolder = false): string => `'use client'
/**
* This configuration is used to for the Sanity Studio that’s mounted on the \`:route:\` route
Expand All @@ -11,8 +11,8 @@ import {defineConfig} from 'sanity'
import {structureTool} from 'sanity/structure'
// Go to https://www.sanity.io/docs/api-versioning to learn how API versioning works
import {apiVersion, dataset, projectId} from './sanity/env'
import {schema} from './sanity/schema'
import {apiVersion, dataset, projectId} from ${hasSrcFolder ? "'./src/sanity/env'" : "'./sanity/env'"}
import {schema} from ${hasSrcFolder ? "'./src/sanity/schema'" : "'./sanity/schema'"}
export default defineConfig({
basePath: ':basePath:',
Expand Down Expand Up @@ -75,8 +75,6 @@ export const projectId = assertValue(
'Missing environment variable: NEXT_PUBLIC_SANITY_PROJECT_ID'
)
export const useCdn = false
function assertValue<T>(v: T | undefined, errorMessage: string): T {
if (v === undefined) {
throw new Error(errorMessage)
Expand All @@ -91,7 +89,6 @@ const envJS = `export const apiVersion =
export const dataset = process.env.NEXT_PUBLIC_SANITY_DATASET;
export const projectId = process.env.NEXT_PUBLIC_SANITY_PROJECT_ID;
export const useCdn = false
`

const schemaTS = `import { type SchemaTypeDefinition } from 'sanity'
Expand All @@ -108,43 +105,38 @@ const schemaJS = `export const schema = {

const client = `import { createClient } from 'next-sanity'
import { apiVersion, dataset, projectId, useCdn } from '../env'
import { apiVersion, dataset, projectId } from '../env'
export const client = createClient({
projectId,
dataset,
apiVersion,
useCdn,
perspective: 'published',
useCdn: true, // Set to false if statically generating pages, using ISR or tag-based revalidation
})
`

const imageTS = `import createImageUrlBuilder from '@sanity/image-url'
import type { Image } from 'sanity'
import { SanityImageSource } from "@sanity/image-url/lib/types/types";
import { dataset, projectId } from '../env'
const imageBuilder = createImageUrlBuilder({
projectId: projectId || '',
dataset: dataset || '',
})
// https://www.sanity.io/docs/image-url
const builder = createImageUrlBuilder({ projectId, dataset })
export const urlForImage = (source: Image) => {
return imageBuilder?.image(source).auto('format').fit('max').url()
export const urlFor = (source: SanityImageSource) => {
return builder.image(source)
}
`

const imageJS = `import createImageUrlBuilder from '@sanity/image-url'
import { dataset, projectId } from '../env'
const imageBuilder = createImageUrlBuilder({
projectId: projectId || '',
dataset: dataset || '',
})
// https://www.sanity.io/docs/image-url
const builder = createImageUrlBuilder({ projectId, dataset })
export const urlForImage = (source) => {
return imageBuilder?.image(source).auto('format').fit('max').url()
export const urlFor = (source) => {
return builder.image(source)
}
`

Expand Down
Loading

0 comments on commit d42da14

Please sign in to comment.