Skip to content

Commit

Permalink
fix: collections default value
Browse files Browse the repository at this point in the history
  • Loading branch information
farnabaz committed Nov 4, 2024
1 parent 6a9eb83 commit 705aab7
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 4 deletions.
12 changes: 10 additions & 2 deletions src/utils/collection.ts
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,11 @@ export function generateCollectionInsert(collection: ResolvedCollection, data: R
const value = (collection.extendedSchema).shape[key]
const underlyingType = getUnderlyingType(value as ZodType<unknown, ZodOptionalDef>)

const defaultValue = value._def.defaultValue ? value._def.defaultValue() : 'NULL'
let defaultValue = value._def.defaultValue ? value._def.defaultValue() : 'NULL'

if (!(defaultValue instanceof Date) && typeof defaultValue === 'object') {
defaultValue = JSON.stringify(defaultValue)
}
const valueToInsert = typeof data[key] !== 'undefined' ? data[key] : defaultValue

fields.push(key)
Expand Down Expand Up @@ -163,9 +167,13 @@ export function generateCollectionTableDefinition(collection: ResolvedCollection

// Handle default values
if (type._def.defaultValue !== undefined) {
const defaultValue = typeof type._def.defaultValue() === 'string'
let defaultValue = typeof type._def.defaultValue() === 'string'
? `'${type._def.defaultValue()}'`
: type._def.defaultValue()

if (!(defaultValue instanceof Date) && typeof defaultValue === 'object') {
defaultValue = `'${JSON.stringify(defaultValue)}'`
}
constraints.push(`DEFAULT ${defaultValue}`)
}

Expand Down
7 changes: 7 additions & 0 deletions src/utils/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,13 @@ export async function loadLayersConfig(nuxt: Nuxt) {
}
}

if (Object.keys(collectionMap).length === 0) {
const collections = resolveCollections(defaultConfig.collections)
for (const collection of collections) {
collectionMap[collection.name] = collection
}
}

return {
collections: Object.values(collectionMap),
}
Expand Down
4 changes: 2 additions & 2 deletions test/unit/generateCollectionTableDefinition.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ describe('generateCollectionTableDefinition', () => {
' "meta" TEXT,',
' "navigation" TEXT DEFAULT true,',
' "path" VARCHAR,',
' "seo" TEXT,',
' "seo" TEXT DEFAULT \'{}\',',
' "stem" VARCHAR,',
' "title" VARCHAR',
');',
Expand All @@ -47,7 +47,7 @@ describe('generateCollectionTableDefinition', () => {
' "meta" TEXT,',
' "navigation" TEXT DEFAULT true,',
' "path" VARCHAR,',
' "seo" TEXT,',
' "seo" TEXT DEFAULT \'{}\',',
' "stem" VARCHAR,',
' "title" VARCHAR',
');',
Expand Down

0 comments on commit 705aab7

Please sign in to comment.