Created
August 1, 2019 14:27
-
-
Save tanc/4f3891ad190320ef321a6f82748071d2 to your computer and use it in GitHub Desktop.
Cockpit to Gridsome - Download assets (images)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require('path') | |
const axios = require('axios') | |
const fs = require('fs') | |
const languages = [ | |
'en', | |
] | |
class gridsomeSetup { | |
static defaultOptions () { | |
return { | |
host: process.env.APIHOST || '' | |
} | |
} | |
constructor (api, options) { | |
api.beforeProcessAssets(prepareImages => { | |
var query = '{ allCockpitAsset { edges { node { title assetPath } } } }' | |
api._app.graphql(query, {}).then(result => { | |
result.data.allCockpitAsset.edges.forEach((edge) => { | |
const url = edge.node.assetPath | |
const filename = url.split('\/').reverse()[0] | |
const localPath = `src/assets/files/${filename}` | |
const remoteUrl = `${options.host}/storage/uploads/${url}` | |
// Check if we already have the image locally. | |
if (fs.existsSync(localPath)) { | |
console.log('File already exists locally: ', localPath) | |
} else { | |
this.downloadAsset(remoteUrl, filename) | |
} | |
}) | |
}) | |
}) | |
} | |
async downloadAsset(url, filename) { | |
console.log('Fetching remote file at:', url) | |
const filePath = path.resolve(__dirname, 'src/assets/files', filename) | |
// axios image download with response type "stream" | |
try { | |
const response = await axios({ | |
method: 'GET', | |
url: url, | |
responseType: 'stream' | |
}) | |
// pipe the result stream into a file on disc | |
response.data.pipe(fs.createWriteStream(filePath)) | |
// return a promise and resolve when download finishes | |
return new Promise((resolve, reject) => { | |
response.data.on('end', () => { | |
resolve() | |
}) | |
response.data.on('error', () => { | |
reject() | |
}) | |
}) | |
} catch (error) { | |
console.log(error) | |
} | |
} | |
} | |
module.exports = gridsomeSetup |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment