1+ import { exec } from "child_process" ;
12import type { Request , Response } from "express" ;
23import { readFileSync } from "fs" ;
3- import sharp from "sharp" ;
4-
5- // eslint-disable-next-line max-len
6- const REGEX_EDGE_URL =
7- / ^ e d g e s \/ (?< countryCode > [ ^ / ] + ) \/ g e n \/ _ ? (?< magazineCode > [ ^ . ] + ) \. (?< issueNumber > [ ^ . ] + ) \. (?< extension > [ ^ ? ] + ) ? (?: \? .+ ) ? $ / ;
4+ import { pipeline } from "stream" ;
85
96const corsHeaders = {
107 "Access-Control-Allow-Origin" : "*" ,
@@ -15,35 +12,36 @@ const corsHeaders = {
1512 "If-Modified-Since,Cache-Control,Content-Type,x-dm-user,x-dm-pass" ,
1613} ;
1714export const get = ( req : Request , res : Response ) => {
18- const input = req . url . replace ( / ^ \/ / , "" ) ;
19- let text ;
20- const match = input . match ( REGEX_EDGE_URL ) ;
21- if ( match ) {
22- const { countryCode, magazineCode, issueNumber, extension } = match . groups ! ;
15+ const { countrycode, magazinecode, issuenumber, extension } = req . params ! ;
2316
24- if ( countryCode && extension !== "png" ) {
25- res . writeHead ( 404 , corsHeaders ) ;
26- res . end ( "" ) ;
27- return ;
28- }
29- text = `${ countryCode } /${ magazineCode } ${ issueNumber } ` ;
30- } else {
31- text = input ;
17+ if ( countrycode && extension !== "png" ) {
18+ res . writeHead ( 404 , corsHeaders ) ;
19+ res . end ( "" ) ;
20+ return ;
3221 }
22+ const text = `${ countrycode } /${ magazinecode } ${ issuenumber } ` ;
23+
24+ const convert = exec ( "convert svg:- png:-" , {
25+ encoding : "buffer" ,
26+ } ) ;
3327
34- const content = Buffer . from (
35- readFileSync ( "assets/default.svg" )
36- . toString ( )
37- . replace ( "My text" , decodeURIComponent ( text ) ) ,
38- "utf8" ,
28+ convert . stdin ! . write (
29+ Buffer . from (
30+ readFileSync ( "assets/default.svg" )
31+ . toString ( )
32+ . replace ( "My text" , decodeURIComponent ( text ) ) ,
33+ "utf8"
34+ )
3935 ) ;
40- sharp ( content ) . toBuffer ( ( error , buffer ) => {
41- if ( error ) {
42- res . writeHead ( 500 , corsHeaders ) ;
43- return res . end ( `Error : ${ JSON . stringify ( { error } ) } ` ) ;
36+ convert . stdin ! . end ( ) ;
37+
38+ res . setHeader ( "Content-Type" , "image/png" ) ;
39+
40+ pipeline ( convert . stdout ! , res , ( err ) => {
41+ if ( err ) {
42+ console . error ( "Pipeline failed" , err ) ;
43+ res . status ( 500 ) . send ( "Conversion failed" ) ;
4444 }
45- res . writeHead ( 200 , { ...corsHeaders , "Content-Type" : "image/png" } ) ;
46- return res . end ( buffer ) ;
4745 } ) ;
4846} ;
4947
0 commit comments