11import { schemaComposer } from 'graphql-compose' ;
22import { composeWithJson } from 'graphql-compose-json' ;
3- import { defaultsDeep , get , merge } from 'lodash-es' ;
3+ import { defaultsDeep , get , merge , set } from 'lodash-es' ;
4+ import { nanoid } from 'nanoid' ;
45import plur from 'plur' ;
56import { VFile } from 'vfile' ;
67
@@ -12,6 +13,7 @@ import {
1213 LoadedFlatbreadConfig ,
1314 Source ,
1415 Transformer ,
16+ CollectionEntry ,
1517} from '../types' ;
1618import { getFieldOverrides } from '../utils/fieldOverrides' ;
1719import { map } from '../utils/map' ;
@@ -108,18 +110,33 @@ export async function generateSchema(
108110 undefined : config . transformer [ 0 ] ,
109111 } ;
110112
111- async function updateCollectionRecord ( entry : EntryNode & { _metadata : any } ) {
112- const { _metadata : ctx , ...record } = entry ;
113- const { serialize } = transformersById [ ctx . transformedBy ] ;
113+ async function updateCollectionRecord (
114+ collection : CollectionEntry ,
115+ entry : EntryNode & { _metadata : any }
116+ ) {
117+ const ctx = entry . _metadata ;
118+ const { serialize, id : transformerId } =
119+ transformersById [ ctx . transformedBy ] ;
120+
121+ if ( ctx . reference ) {
122+ const index = allContentNodesJSON [ ctx . collection ] . findIndex (
123+ ( c ) => get ( c , ctx . referenceField ) === ctx . reference
124+ ) ;
125+
126+ if ( index < 0 ) throw new Error ( 'Failed to find record to update' ) ;
127+ // replace in memory representation of record
128+ allContentNodesJSON [ ctx . collection ] [ index ] = entry ;
129+ } else {
130+ entry . _metadata . reference = nanoid ( ) ;
131+ set ( entry , entry . _metadata . referenceField , entry . _metadata . reference ) ;
132+ entry . _metadata . transformedBy = transformerId ;
133+ allContentNodesJSON [ ctx . collection ] . push ( entry ) ;
134+ }
135+
136+ const { _metadata, ...record } = entry ;
114137 const file = await serialize ( record , ctx . transformContext ) ;
138+ await config ?. source . put ( file , ctx . sourceContext , ctx ) ;
115139
116- await config ?. source . put ( file , ctx . sourceContext ) ;
117- const index = allContentNodesJSON [ ctx . collection ] . findIndex (
118- ( c ) => get ( c , ctx . referenceField ) === ctx . reference
119- ) ;
120-
121- // replace in memory representation of record
122- allContentNodesJSON [ ctx . collection ] [ index ] = entry ;
123140 return entry ;
124141 }
125142
@@ -143,6 +160,8 @@ export async function generateSchema(
143160 /// Query resolvers
144161 //
145162
163+ // TODO: add a new type of plugin that can add resolvers to each collection, they should be called here
164+
146165 addCollectionQueries ( {
147166 name,
148167 pluralName,
@@ -160,6 +179,7 @@ export async function generateSchema(
160179 schemaComposer,
161180 updateCollectionRecord,
162181 config,
182+ collectionEntry : config . content . find ( ( c ) => c . name === name ) ,
163183 } ) ;
164184 }
165185
0 commit comments