11import { Emails } from "@watonomous/watcloud-email-templates" ;
22import { FissionContext , FissionCallback } from "./utils" ;
3+ import { render } from "@react-email/components" ;
4+ import { waitForAssets } from "@repo/utils/watcloud-uri" ;
35
4- module . exports = async function ( { request, response} : FissionContext , cb : FissionCallback ) {
5- response . status ( 200 ) . json ( {
6- templates : Object . keys ( Emails ) ,
7- } ) ;
6+ // Returns the email template with the given name and performs any necessary initialization.
7+ async function getTemplate ( template_name : string , props_array : any [ ] = [ ] ) {
8+ const mod = Emails [ template_name ] ;
9+ if ( ! mod ) {
10+ throw new Error ( `Template ${ template_name } not found` ) ;
11+ }
12+ if ( mod . init ) {
13+ await Promise . all ( props_array . map ( mod . init ) ) ;
14+ }
15+ await waitForAssets ( ) ;
16+
17+ return mod . default ;
18+ }
19+
20+ module . exports = async function ( { request, response } : FissionContext , cb : FissionCallback ) {
21+ if ( request . method !== "POST" ) {
22+ response . status ( 405 ) . json ( {
23+ error : "Only POST is supported" ,
24+ } ) ;
25+ return ;
26+ }
27+
28+ const template_name = request . body ?. template ;
29+ if ( ! template_name ) {
30+ response . status ( 400 ) . json ( {
31+ error : "Missing template! Supported templates: " + Object . keys ( Emails ) . join ( ", " ) ,
32+ } ) ;
33+ return ;
34+ }
35+
36+ const props = request . body ?. props ;
37+ if ( ! props ) {
38+ response . status ( 400 ) . json ( {
39+ error : "Missing props" ,
40+ } ) ;
41+ return ;
42+ }
43+
44+ if ( ! Emails [ template_name ] ) {
45+ response . status ( 400 ) . json ( {
46+ error : `Template "${ template_name } " not found! Supported templates: ${ Object . keys ( Emails ) . join ( "," ) } ` ,
47+ } ) ;
48+ return ;
49+ }
50+
51+ const template = await getTemplate ( template_name , [ props ] ) ;
52+
53+ const htmlPromise = render ( template ( props ) ) ;
54+ const textPromise = render ( template ( props ) , { plainText : true } ) ;
55+
56+ try {
57+ const payload = {
58+ html : await htmlPromise ,
59+ text : await textPromise ,
60+ } ;
61+
62+ response . status ( 200 ) . json ( payload ) ;
63+ } catch ( e ) {
64+ console . error ( e ) ;
65+ response . status ( 500 ) . json ( {
66+ error : "Failed to render email: " + e ,
67+ } ) ;
68+ return ;
69+ }
870}
0 commit comments