Я использую библиотеку exceljs. Он отлично работает на моем локальном сервере node. Теперь я пытаюсь использовать функции Firebase для загрузки файла excel в облачное хранилище Google.
Это весь код, который я использую:
'use strict';
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const ExcelJS = require('exceljs');
admin.initializeApp();
var workbook = new ExcelJS.Workbook();
var worksheet = workbook.addWorksheet('Relatório Consolidado');
function startExcel(){
worksheet.columns = [
{ header: 'Empresa', key: 'empresa', width: 25 },
{ header: 'Data criação', key: 'data_criacao', width: 25 },
{ header: 'Responsável agendamento', key: 'agendador', width: 25 },
{ header: 'Colaborador', key: 'colaborador', width: 25 },
{ header: 'Endereço', key: 'endereco', width: 25 },
{ header: 'CPF', key: 'cpf', width: 25 },
{ header: 'CTPS', key: 'ctps', width: 25 },
{ header: 'Função', key: 'funcao', width: 25 },
{ header: 'Data agendado', key: 'nome_subtipo_produto', width: 25 },
{ header: 'Data atendimento médico', key: 'nome_subtipo_produto', width: 25 },
{ header: 'Data inicio atendimento', key: 'nome_subtipo_produto', width: 25 },
{ header: 'Data inicio exames', key: 'nome_subtipo_produto', width: 25 },
{ header: 'Tipo de exame', key: 'valor_produto', width: 25 },
{ header: 'Exames realizados', key: 'valor_produto', width: 25 },
{ header: 'Status atendimento', key: 'tipoPagamento', width: 25 },
{ header: 'Status exames', key: 'centroCustoStr', width: 25 }
];
}
function salvaExcel(){
return new Promise(function(resolve, reject){
let filename = `/tmp/Relatorio.xlsx`
let bucketName = 'gs://xxx.appspot.com/Relatorios'
const bucket = admin.storage().bucket(bucketName);
workbook.xlsx.writeFile(filename)
.then(() => {
console.log('Excel criado com sucesso! Enviando upload do arquivo: ' + filename)
const metadata = {
contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
};
bucket.upload(filename, metadata)
.then(() => {
const theFile = bucket.file(filename);
theFile.getSignedURL(signedUrlOptions)
.then((signedUrl) => {
resolve(signedUrl)
});
})
.catch((error) => {
reject('Erro ao realizar upload: ' + error)
})
})
.catch((error) => {
reject('Erro ao realizar upload: ' + error)
})
})
}
startExcel()
/**********************************
* Relatórios
********************************/
function relatorios(change, context){
return new Promise((resolve, reject) => {
const snapshot = change.after
const data = snapshot.val()
verificaRelatorioAgendamentos(change)
.then(() => {
resolve()
})
.catch((error => {
reject(error)
}))
})
}
function verificaRelatorioAgendamentos(change, context){
return new Promise((resolve, reject) => {
const snapshot = change.after
const data = snapshot.val()
const dataInicial = data.dataInicial
const year = moment(dataInicial).format('YYYY')
const month = moment(dataInicial).format('MM')
const state = 'DF'
let path = "/agendamentos/" + state + "/" + year + "/" + month
const relatorios = admin.database().ref(path).once('value');
return Promise.all([relatorios])
.then(results => {
let valores = results[0]
criaRelatorioAgendamentos(valores)
.then(() => {
resolve()
})
.catch((error => {
reject(error)
}))
})
})
}
function criaRelatorioAgendamentos(results){
return new Promise((resolve, reject) => {
let promises = []
results.forEach(element => {
let promise = new Promise(function(resolveExcel){
let data = element.val()
worksheet.addRow({
id: 1,
empresa: data.agendador.company,
data_criacao: data.dataCriacao,
agendador: data.agendador.nome,
colaborador: data.colaborador.nome,
cpf: data.colaborador.cpf,
ctps: data.colaborador.ctps,
funcao: data.colaborador.funcao,
data_agendado: data.data,
data_atendimento_medico: data.dataAtendimento,
data_inicio_atendimento: data.dataInicio,
data_inicio_exames: data.dataInicioExames,
tipo_exame: data.tipoExame,
exames: data.exames[0].nome,
status_atendimento: data.status,
status_exames: data.statusExames
})
resolveExcel()
})
promises.push(promise)
})
Promise.all(promises)
.then(() => {
salvaExcel()
.then((url) => {
console.log('Salvar URL' + url)
resolve(url)
})
.catch((error => {
reject(error)
}))
})
})
}
exports.relatorios = functions.database.ref('/relatorios/{state}/{year}/{month}/{relatoriosId}')
.onWrite((change, context) => {
return relatorios(change, context)
});
На консоли функций журнал показывает мне, что файл excel был успешно создан. Но при загрузке выскакивает очень странная ошибка:
Что я делаю неправильно? Я ценю любую помощь.
Спасибо!
return new Promise
в JavaScript с большим количеством промисов внутри, это поднимает флаги, что промисы не обрабатываются должным образом. Не похоже, что вы делаете здесь что-то, что требуетnew Promise
. - person Doug Stevenson   schedule 19.02.2020