11import { Router } from "express" ;
2+ import formidable from "formidable" ;
23const router = Router ( ) ;
34import { bake , Dish } from "cyberchef/src/node/index.mjs" ;
45
56/**
67 * bakePost
78 */
89router . post ( "/" , async function bakePost ( req , res , next ) {
10+ if ( req . is ( "multipart/form-data" ) ) {
11+ bakeMultipartForm ( req , res , next ) ;
12+ } else {
13+ bakeBody ( req , res , next ) ;
14+ }
15+ } ) ;
16+
17+ async function bakeMultipartForm ( req , res , next ) {
18+ const form = formidable ( ) ;
19+
20+ try {
21+
22+ form . parse ( req , async ( err , fields , files ) => {
23+
24+ // req.log.warn(`Recipe: ${fields.recipe}`);
25+ // req.log.warn(`Input: ${files.input}`);
26+ // req.log.warn(`Other input: ${fields.input}`);
27+ if ( err ) {
28+ throw err ;
29+ }
30+
31+ if ( ! ( 'recipe' in fields ) ) {
32+ throw new Error ( "Could not find required 'recipe' field in multipart form data" ) ;
33+ }
34+
35+ let dish ;
36+
37+ // Case: data is in files.input
38+ if ( 'input' in files ) {
39+ // read the contents of the file and use it as an input
40+ res . json ( { fields, files } ) ;
41+ } else if ( 'input' in fields ) {
42+
43+ dish = await bake ( fields . input , fields . recipe ) ;
44+
45+ } else {
46+ throw new Error ( "Could not find 'input' field in multipart form data." ) ;
47+ }
48+
49+ // Attempt to translate to another type. Any translation errors
50+ // propagate through to the errorHandler.
51+ if ( 'outputType' in fields ) {
52+ dish . get ( req . body . outputType ) ;
53+ }
54+
55+ if ( dish ) {
56+ res . send ( {
57+ value : dish . value ,
58+ type : Dish . enumLookup ( dish . type ) ,
59+ } ) ;
60+ }
61+
62+ } ) ;
63+
64+ } catch ( e ) {
65+ next ( e ) ;
66+ }
67+ }
68+
69+ async function bakeBody ( req , res , next ) {
70+
971 try {
1072 if ( ! req . body . input ) {
1173 throw new TypeError ( "'input' property is required in request body" ) ;
@@ -31,6 +93,6 @@ router.post("/", async function bakePost(req, res, next) {
3193 } catch ( e ) {
3294 next ( e ) ;
3395 }
34- } ) ;
96+ }
3597
3698export default router ;
0 commit comments