#!/usr/bin/env node -r babel/register

import fs from 'fs'
import path from 'path'
import { graphql } from 'graphql'
import loadModels from '../models'
import * as config from '../config'
import loadSchema from '../db/schema'
import { introspectionQuery, printSchema } from 'graphql/utilities'

export async function updateSchema () {
  const models = loadModels(config.database)
  const Schema = loadSchema(models)

  const result = await graphql(Schema, introspectionQuery)
  if (result.errors) {
    console.error(
      'ERROR introspecting schema: ',
      JSON.stringify(result.errors, null, 2)
    )
  } else {
    fs.writeFileSync(
      path.join(__dirname, '../db/schema.json'),
      JSON.stringify(result, null, 2)
    )
  }

  fs.writeFileSync(
    path.join(__dirname, '../db/schema.graphql'),
    printSchema(Schema)
  )
}

if (require.main === module) {
  updateSchema().then(
    () => console.log('finished'),
    (err) => console.error('error', err)
  )
}

@@ -545,17 +545,16 @@
  schema:
- 
 ',%0A     
@@ -605,24 +605,61 @@
 )%0A  
-%7D else %7B%0A    fs.
+  throw result.errors%0A  %7D%0A%0A  await Promise.all(%5B%0A    
 writ
@@ -659,28 +659,31 @@
    writeFile
-Sync
+Promise
 (%0A      path
@@ -768,19 +768,14 @@
    )
+,
 %0A  
-%7D%0A%0A  fs.
+  
 writ
@@ -783,14 +783,19 @@
 File
-Sync(%0A
+Promise(%0A  
     
@@ -844,16 +844,18 @@
 '),%0A    
+  
 printSch
@@ -864,24 +864,31 @@
 a(Schema)%0A  
+  )%0A  %5D
 )%0A%7D%0A%0Aif (req
@@ -1012,12 +1012,194 @@
  err)%0A  )%0A%7D%0A
+%0Afunction writeFilePromise (filePath, file) %7B%0A  return new Promise((resolve, reject) =%3E %7B%0A    fs.writeFile(filePath, file, err =%3E %7B%0A      err ? reject(err) : resolve()%0A    %7D)%0A  %7D)%0A%7D%0A

Clean up update-schema script