Skip to content

Commit

Permalink
🚧 WIP download answer
Browse files Browse the repository at this point in the history
  • Loading branch information
MaloLebrin committed Feb 10, 2023
1 parent 743e509 commit ae9416a
Show file tree
Hide file tree
Showing 5 changed files with 103 additions and 35 deletions.
29 changes: 23 additions & 6 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,17 +1,25 @@
FROM node:18.14
FROM zenika/alpine-chrome:with-puppeteer

RUN mkdir /app
USER root

RUN git config --system --add safe.directory '*'

RUN apk add --no-cache ttf-liberation

# RUN mkdir /app
WORKDIR /app

COPY package.json /app/
COPY pnpm-lock.yaml /app/

# RUN npm install
RUN npm i -g pnpm
RUN npm i -g @antfu/ni

RUN nci
RUN pnpm install --frozen-lockfile --unsafe-perm \
&& chown -R 0:0 /app/node_modules

# RUN mkdir node_modules/.cache
RUN chmod -R 777 node_modules/.cache
# Be careful with this env variable
ARG NODE_ENV
ENV NODE_ENV=${NODE_ENV}
Expand All @@ -23,8 +31,17 @@ COPY entrypoint.sh /app/
COPY scriptSeed.sh /app/
COPY ./src /app/src

RUN nr tsc
RUN pnpm run tsc

RUN chmod +x /app/entrypoint.sh
RUN chmod +x /app/scriptSeed.sh
ENTRYPOINT ["/bin/bash","/app/entrypoint.sh"]

# RUN mkdir /app/uploads
RUN chmod -R 777 /app/uploads
RUN chmod 777 /app/build/src/middlewares/

USER chrome
RUN chmod +x /app/uploads

ENTRYPOINT ["node", "/app/build/src/index.js"]
# ENTRYPOINT ["/bin/bash","/app/entrypoint.sh"]
17 changes: 9 additions & 8 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ services:

app:
restart: always
image: zenika/alpine-chrome:with-puppeteer
links:
- redis
depends_on:
Expand All @@ -33,14 +34,14 @@ services:
env_file:
- .env

cron:
depends_on:
- postgres
build:
context: .
dockerfile: ./cron.Dockerfile
env_file:
- .env
# cron:
# depends_on:
# - postgres
# build:
# context: .
# dockerfile: ./cron.Dockerfile
# env_file:
# - .env


volumes:
Expand Down
89 changes: 69 additions & 20 deletions src/controllers/DownloadController.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import path from 'path'
import { unlink } from 'fs'
import type { Request, Response } from 'express'
import puppeteer from 'puppeteer'
import type { Logger } from 'pino'
import { APP_SOURCE } from '..'
import { ApiError } from '../middlewares/ApiError'
// import type RedisCache from '../RedisCache'
Expand All @@ -11,22 +12,35 @@ import { wrapperRequest } from '../utils'
import UserService from '../services/UserService'
import { AddressService } from '../services'
import type { EmployeeEntity } from '../entity/EmployeeEntity'
import { useLogger } from '../middlewares/loggerService'

export default class AuthController {
AnswerService: AnswerService
AddressService: AddressService
EventService: EventService
UserService: UserService
logger: Logger<{
transport: {
target: string
options: {
colorize: boolean
}
}
}>
// redisCache: RedisCache

constructor() {
this.AnswerService = new AnswerService(APP_SOURCE)
this.AddressService = new AddressService(APP_SOURCE)
this.UserService = new UserService(APP_SOURCE)
this.EventService = new EventService(APP_SOURCE)
this.logger = useLogger().logger
// this.redisCache = REDIS_CACHE
}

// eslint-disable-next-line promise/param-names
private delay = async (ms: number) => new Promise(res => setTimeout(res, ms))

public ViewAnswer = async (req: Request, res: Response) => {
await wrapperRequest(req, res, async () => {
const id = parseInt(req.params.id)
Expand Down Expand Up @@ -77,30 +91,65 @@ export default class AuthController {
const employee = answer?.employee as EmployeeEntity
if (employee) {
const baseUrl = `${req.protocol}://${req.get('host')}`
const url = `${baseUrl}answer/download/1`
const url = `${baseUrl}/answer/view/${id}`
console.log(url, '<==== url')
// const url = `${baseUrl}/orders/${id}/view`

const filePath = path.resolve(__dirname, `../../public/ANSWER-${employee.slug}.pdf`)

const browser = await puppeteer.launch({
headless: true,
executablePath: '/usr/bin/chromium-browser',
args: [
'--no-sandbox',
'--disable-gpu',
],
})

const page = await browser.newPage()

await page.goto(url)
await page.pdf({ path: filePath, format: 'a4', printBackground: true })
await browser.close()

return res.download(filePath)
const filePath = `/app/uploads/ANSWER-${employee.slug}.pdf`

try {
const browser = await puppeteer.launch({
headless: true,
executablePath: '/usr/bin/chromium-browser',
args: [
'--no-sandbox',
'--disable-gpu',
],
})

const page = await browser.newPage()

await page.goto(url)
const pdf = await page.pdf({ path: filePath, format: 'a4', printBackground: true })
await browser.close()

return res
.set({ 'Content-Type': 'application/pdf', 'Content-Length': pdf.length })
.download(filePath)
} catch (error) {
this.logger.error(error)
return res.status(error.status || 500).send({
success: false,
message: error.message,
stack: error.stack,
description: error.cause,
})
} finally {
await this.delay(1000)

// eslint-disable-next-line security/detect-non-literal-fs-filename
unlink(filePath, err => {
if (err) {
this.logger.error(err)
return res.status(422).send({
success: false,
message: err.message,
stack: err.stack,
description: err.cause,
})
} else {
this.logger.info(`${filePath} was deleted`)
}
})
}
}
}
// throw new ApiError(422, 'L\'identifiant de la réponse est requis').Handler(res)
})
}

public getPDFAnswer = async (req: Request, res: Response) => {
await wrapperRequest(req, res, async () => {
})
}
}
1 change: 1 addition & 0 deletions src/env.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,5 +18,6 @@ export function useEnv() {
REDIS_PASSWORD: process.env.REDIS_PASSWORD,
REDIS_PORT: process.env.REDIS_PORT,
GEO_CODING_API_URL: process.env.GEO_CODING_API_URL,
API_PDF_URL: process.env.API_PDF_URL,
}
}
2 changes: 1 addition & 1 deletion src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ async function StartApp() {
.then(async () => {
logger.info('Data Source has been initialized!')

if (NODE_ENV === 'test') {
if (NODE_ENV !== 'test') {
logger.info('seeders started')
await seedersFunction(APP_SOURCE)
logger.info('seeders ended')
Expand Down

0 comments on commit ae9416a

Please sign in to comment.