Created
April 30, 2021 00:00
-
-
Save roqbez/a4612350f222ce116041241fe7d2560a to your computer and use it in GitHub Desktop.
Node.js + Nest.js code to import Excel file to a database
This file contains hidden or 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
import { HttpService, Injectable, Logger } from '@nestjs/common'; | |
import { InjectModel } from '@nestjs/sequelize'; | |
import { ReadStream } from 'fs'; | |
import { Sequelize } from 'sequelize-typescript'; | |
import * as xlsx from 'xlsx'; | |
import { WorkBook, WorkSheet } from 'xlsx'; | |
import { ArquivoImportacao } from './dto/arquivo-importacao.dto'; | |
@Injectable() | |
export class ImportacaoProcessosService { | |
private readonly logger = new Logger(ImportacaoProcessosService.name); | |
constructor( | |
private httpService: HttpService, | |
private sequelize: Sequelize, | |
@InjectModel(ImportacaoProcesso) | |
private importacaoProcessoModel: typeof ImportacaoProcesso, | |
) { } | |
async carregarArquivo(arquivo: ArquivoImportacao) { | |
try { | |
const res = await this.httpService | |
.get(arquivo.url, { responseType: 'stream' }) | |
.toPromise(); | |
if (res.status !== 200) { | |
throw new Error('Erro obtendo o arquivo ' + arquivo.url); | |
} | |
const wb: WorkBook = await new Promise((resolve, reject) => { | |
const stream: ReadStream = res.data; | |
const buffers = []; | |
stream.on('data', (data) => buffers.push(data)); | |
stream.on('end', () => { | |
const buffer = Buffer.concat(buffers); | |
resolve(xlsx.read(buffer, { type: 'buffer' })); | |
}); | |
stream.on('error', (error) => reject(error)); | |
}); | |
const sheet: WorkSheet = wb.Sheets[wb.SheetNames[0]]; | |
const range = xlsx.utils.decode_range(sheet['!ref']); | |
await this.sequelize.transaction(async tx => { | |
for (let R = range.s.r; R <= range.e.r; ++R) { | |
if (R === 0 || !sheet[xlsx.utils.encode_cell({ c: 0, r: R })]) { | |
continue; | |
} | |
let col = 0; | |
const entity = { | |
processoSei: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
processoJudicial: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
varaProcesso: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
secaoJudiciaria: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
tribunal: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
autorNome: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
autorCpf: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
autorUF: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
reus: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
objetoAcao: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
descricao: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
enfermidade: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
dataUltimaReceita: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
dataUltimoCumprimento: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
periodoUltimoCumprimento: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
advogado: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
determinacao: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v, | |
observacoesProcesso: sheet[xlsx.utils.encode_cell({ c: col++, r: R })]?.v | |
}; | |
const pk = sheet[xlsx.utils.encode_cell({ c: 0, r: R })].v; | |
const exists = (await this.importacaoProcessoModel.count({ where: { processoSei: pk }, transaction: tx })) > 0; | |
if (exists) { | |
await this.importacaoProcessoModel.update(entity, { where: { processoSei: pk }, transaction: tx }); | |
} else { | |
await this.importacaoProcessoModel.create(entity, { transaction: tx }); | |
} | |
} | |
}); | |
} catch (error) { | |
this.logger.error('Erro carregando arquivo do Excel'); | |
throw error; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment