1+ // Retrieves file and returns as json object
2+ async function retrieveFile ( filePath ) {
3+ try {
4+ const response = await fetch ( filePath ) ;
5+
6+ if ( ! response . ok ) {
7+ throw new Error ( 'Network response was not ok' ) ;
8+ }
9+ // Returns file contents in a json format
10+ return await response . json ( ) ;
11+ } catch ( error ) {
12+ console . error ( 'There was a problem with the fetch operation:' , error ) ;
13+ return null ;
14+ }
15+ }
16+
17+ // Populates blank code.json object with values from form
18+ function populateObject ( data , blankObject ) {
19+ for ( let key in data ) {
20+ console . log ( "current key" , key )
21+ console . log ( "check if value exists" , data . hasOwnProperty ( key ) )
22+ if ( blankObject . hasOwnProperty ( key ) ) {
23+ if ( typeof data [ key ] === 'object' && data [ key ] !== null ) {
24+ // If object, recursively populate
25+ // TODO: test out for permissions and description objects
26+ populateObject ( data [ key ] , blankObject [ key ] ) ;
27+ } else {
28+ // Add value
29+ blankObject [ key ] = data [ key ] ;
30+ }
31+ }
32+ }
33+ }
34+
35+ async function populateCodeJson ( data ) {
36+ // Path to the blank json file
37+ const filePath = 'schemas/template-code.json' ;
38+
39+ var codeJson = await retrieveFile ( filePath ) ;
40+
41+ if ( codeJson ) {
42+ populateObject ( data , codeJson ) ;
43+ } else {
44+ console . error ( "Failed to retrieve JSON data." ) ;
45+ }
46+
47+ console . log ( "FINAL CODE JSON HERE" , codeJson ) ;
48+ return codeJson ;
49+ }
50+
51+ // Creates code.json and triggers file download
52+ async function downloadFile ( data ) {
53+ delete data . submit ;
54+ const codeJson = await populateCodeJson ( data ) ;
55+
56+ const jsonString = JSON . stringify ( codeJson , null , 2 ) ;
57+ const blob = new Blob ( [ jsonString ] , { type : 'application/json' } ) ;
58+
59+ // Create anchor element and create download link
60+ const link = document . createElement ( 'a' ) ;
61+ link . href = URL . createObjectURL ( blob ) ;
62+ link . download = "code.json" ;
63+
64+ // Trigger the download
65+ link . click ( ) ;
66+ }
67+
68+ window . downloadFile = downloadFile ;
0 commit comments