Skip to content

Commit

Permalink
fix: promise to async
Browse files Browse the repository at this point in the history
  • Loading branch information
pimlie committed Jan 8, 2019
1 parent ae4b0eb commit 0456ffd
Show file tree
Hide file tree
Showing 2 changed files with 106 additions and 87 deletions.
185 changes: 99 additions & 86 deletions lib/module.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import defaults from 'lodash.defaults'
import defaultsDeep from 'lodash.defaultsdeep'
import mkdirp from 'mkdirp'
import consolaLib from 'consola'
import { fromBuffer } from 'yauzl'
import yauzl from 'yauzl'

import {
isUrl,
Expand All @@ -18,7 +18,7 @@ import {
extractZipfile
} from './utils'

const yauzlFromBuffer = promisify(fromBuffer)
const yauzlFromBuffer = promisify(yauzl.fromBuffer)
const consola = consolaLib.withScope('rfg-icon')

export default function nuxtRfgIcon(options) {
Expand All @@ -33,7 +33,7 @@ export default function nuxtRfgIcon(options) {
this.options.head = {}
}

this.nuxt.hook('build:before', (builder) => {
this.nuxt.hook('build:before', async (builder) => {
const faviconConfig = defaultsDeep(this.options['rfg-icon'] || options || {}, rfgDefaults)

if (faviconConfig.static) {
Expand Down Expand Up @@ -118,105 +118,118 @@ export default function nuxtRfgIcon(options) {
faviconConfig.rfg.apiKey = faviconConfig.apiKey
faviconConfig.rfg.masterPicture = faviconConfig.masterPicture || path.resolve(this.options.srcDir, 'static', 'icon.png')

let headers
rfgApiRequestMeta(faviconConfig)
.then(({ data }) => {
headers = data.favicon_generation_result.favicon.html_code

return rfgApiRequestPackage(faviconConfig, data.favicon_generation_result.favicon.package_url)
}).then(({ data }) => {
return yauzlFromBuffer(data)
}).then((zipFile) => {
return extractZipfile(zipFile)
}).then((zipEntries) => {
return zipEntries
}).then((faviconFiles) => {
// add link and meta's to head
const options = {}
options.head = headersToJson(headers)
try {
const { data: metaData } = await rfgApiRequestMeta(faviconConfig)
if (!metaData) {
consola.warn('Received empty meta data from api')
return
}

// apply manifest to current manifest, use defaults so you can still override values
const manifest = find(faviconFiles, { fileName: 'manifest.json' })
options.manifest = JSON.parse(manifest.buff.toString('UTF-8'))
const { data: zipData } = await rfgApiRequestPackage(faviconConfig, metaData.favicon_generation_result.favicon.package_url)
if (!zipData) {
consola.warn('Received empty zip data from api')
return
}

for (const type in options) {
const json = options[type]
const zipFile = await yauzlFromBuffer(zipData)
if (!zipFile) {
consola.warn('Could not open zip file')
return
}

/* istanbul ignore if */
if (!this.options[type]) {
this.options[type] = {}
}
const faviconFiles = await (await extractZipfile(zipFile))
if (!faviconFiles || !faviconFiles.length) {
consola.warn('Could not extract files from zip file')
return
}

if (type === 'manifest') {
// apply manifest to current manifest, use defaults so you can still override values
this.options[type] = defaults(this.options[type], json)
} else {
for (const key in json) {
/* istanbul ignore if */
if (!Array.isArray(this.options[type][key])) {
this.options[type][key] = []
}
// add link and meta's to head
const options = {}
const headers = metaData.favicon_generation_result.favicon.html_code
options.head = headersToJson(headers)

for (let i = 0; i < json[key].length; i++) {
const row = json[key][i]
// apply manifest to current manifest, use defaults so you can still override values
const manifest = find(faviconFiles, { fileName: 'manifest.json' })
options.manifest = JSON.parse(manifest.buff.toString('UTF-8'))

this.options[type][key].push(row)
}
for (const type in options) {
const json = options[type]

/* istanbul ignore if */
if (!this.options[type]) {
this.options[type] = {}
}

if (type === 'manifest') {
// apply manifest to current manifest, use defaults so you can still override values
this.options[type] = defaults(this.options[type], json)
} else {
for (const key in json) {
/* istanbul ignore if */
if (!Array.isArray(this.options[type][key])) {
this.options[type][key] = []
}

for (let i = 0; i < json[key].length; i++) {
const row = json[key][i]

this.options[type][key].push(row)
}
}
}
}

// always save favicon.ico in static root
const favicon = find(faviconFiles, { fileName: 'favicon.ico' })
fs.writeFileSync(path.resolve(this.options.srcDir, 'static', 'favicon.ico'), favicon.buff, (err) => {
/* istanbul ignore next */
if (err) {
consola.error('Could not save favicon.ico', err)
}
})
// always save favicon.ico in static root
const favicon = find(faviconFiles, { fileName: 'favicon.ico' })
fs.writeFileSync(path.resolve(this.options.srcDir, 'static', 'favicon.ico'), favicon.buff, (err) => {
/* istanbul ignore next */
if (err) {
consola.error('Could not save favicon.ico', err)
}
})

if (faviconConfig.static) {
// add headers
faviconFiles.push({ fileName: 'headers.json', buff: JSON.stringify(options.head) })
if (faviconConfig.static) {
// add headers
faviconFiles.push({ fileName: 'headers.json', buff: JSON.stringify(options.head) })

const iconDir = path.resolve(this.options.srcDir, 'static', faviconConfig.staticPath)
const iconDir = path.resolve(this.options.srcDir, 'static', faviconConfig.staticPath)

return Promise.all(faviconFiles.map(file => new Promise((resolve, reject) => {
fs.writeFile(path.resolve(iconDir, file.fileName), file.buff, (err) => {
/* istanbul ignore if */
if (err) {
consola.error('Could not save file:', 'static/' + faviconConfig.staticPath + '/' + file.fileName, ', err:', err)
}
resolve()
})
}))).then(() => {
consola.success('Finished saving favicons to static folder')
}).catch((err) => {
/* istanbul ignore next */
consola.error(err)
return Promise.all(faviconFiles.map(file => new Promise((resolve, reject) => {
fs.writeFile(path.resolve(iconDir, file.fileName), file.buff, (err) => {
/* istanbul ignore if */
if (err) {
consola.error('Could not save file:', 'static/' + faviconConfig.staticPath + '/' + file.fileName, ', err:', err)
}
resolve()
})
} else {
// Register webpack plugin to emit icons
this.options.build.plugins.push({
apply(compiler) {
compiler.plugin('emit', function (compilation, _cb) {
faviconFiles.forEach((file) => {
if (file.fileName !== 'manifest.json') {
compilation.assets['icons/' + file.fileName] = {
source: () => file.buff,
size: () => file.buff.length
}
}))).then(() => {
consola.success('Finished saving favicons to static folder')
}).catch((err) => {
/* istanbul ignore next */
consola.error(err)
})
} else {
// Register webpack plugin to emit icons
this.options.build.plugins.push({
apply(compiler) {
compiler.plugin('emit', function (compilation, _cb) {
faviconFiles.forEach((file) => {
if (file.fileName !== 'manifest.json') {
compilation.assets['icons/' + file.fileName] = {
source: () => file.buff,
size: () => file.buff.length
}
})
_cb()
}
})
}
})
}
consola.success('Finished adding favicons as assets')
}).catch((err) => {
_cb()
})
}
})
}
consola.success('Finished adding favicons as assets')
} catch (err) {
/* istanbul ignore next */
consola.error('error while communicating with rfg api', err)
})
consola.error('error while communicating with rfg api', err)
}
})
}
8 changes: 7 additions & 1 deletion lib/utils.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
import axios from 'axios'
const rfg = require('rfg-api').init()
import rfgInit from 'rfg-api'

// remove require's, we dont need them and the dependencies are bugged
const init = rfgInit.init.toString().replace(/require\([^)]+\)/g, '{}')

// EVIL IS HERE (but not really though)
const rfg = eval(`(${init})()`) // eslint-disable-line no-eval

export const fixUrl = url => url.replace(/\/\//g, '/').replace(':/', '://')
export const isUrl = url => url.indexOf('http') === 0 || url.indexOf('//') === 0
Expand Down

0 comments on commit 0456ffd

Please sign in to comment.