@@ -5,9 +5,66 @@ const Backend = require('./');
55module . exports = function next ( conn , options ) {
66 const backend = Backend ( conn , options ?. studioConnection , options ) ;
77
8- return function wrappedNextJSFunction ( req , res ) {
9- const params = { ...req . query , ...req . body , ...req . params } ;
8+ const mothershipUrl = options ?. _mothershipUrl || 'https://mongoose-js.netlify.app/.netlify/functions' ;
9+ let workspace = null ;
10+
11+ return async function wrappedNextJSFunction ( req , res ) {
12+ const params = { ...req . query , ...req . body , ...req . params , authorization : req . headers . authorization } ;
1013 const actionName = params ?. action ;
14+
15+ const authorization = params ?. authorization ;
16+ if ( options ?. apiKey ) {
17+ if ( ! authorization ) {
18+ throw new Error ( 'Not authorized' ) ;
19+ }
20+
21+ if ( workspace == null ) {
22+ ( { workspace } = await fetch ( `${ mothershipUrl } /getWorkspace` , {
23+ method : 'POST' ,
24+ body : JSON . stringify ( { apiKey : options . apiKey } ) ,
25+ headers : {
26+ Authorization : `Bearer ${ options . apiKey } ` ,
27+ 'Content-Type' : 'application/json'
28+ }
29+ } )
30+ . then ( response => {
31+ if ( response . status < 200 || response . status >= 400 ) {
32+ return response . json ( ) . then ( data => {
33+ throw new Error ( `Error getting workspace ${ response . status } : ${ require ( 'util' ) . inspect ( data ) } ` ) ;
34+ } ) ;
35+ }
36+ return response ;
37+ } )
38+ . then ( res => res . json ( ) ) ) ;
39+ }
40+
41+ const { user, roles } = await fetch ( `${ mothershipUrl } /me?` , {
42+ method : 'POST' ,
43+ body : JSON . stringify ( { workspaceId : workspace . _id } ) ,
44+ headers : {
45+ Authorization : authorization ,
46+ 'Content-Type' : 'application/json'
47+ }
48+ } )
49+ . then ( response => {
50+ if ( response . status < 200 || response . status >= 400 ) {
51+ return response . json ( ) . then ( data => {
52+ throw new Error ( `Mongoose Studio API Key Error ${ response . status } : ${ require ( 'util' ) . inspect ( data ) } ` ) ;
53+ } ) ;
54+ }
55+ return response ;
56+ } )
57+ . then ( res => res . json ( ) ) ;
58+ if ( ! user || ! roles ) {
59+ throw new Error ( 'Not authorized' ) ;
60+ }
61+
62+ params . $workspaceId = workspace . _id ;
63+ params . roles = roles ;
64+ params . userId = user . _id ;
65+ params . initiatedById = user . _id ;
66+ }
67+
1168 if ( typeof actionName !== 'string' ) {
1269 throw new Error ( 'No action specified' ) ;
1370 }
@@ -24,7 +81,10 @@ module.exports = function next(conn, options) {
2481 }
2582
2683 return actionFn ( params )
27- . then ( result => res . status ( 200 ) . json ( result ) )
84+ . then ( result => {
85+ res . status ( 200 ) . json ( result ) ;
86+ return result ;
87+ } )
2888 . catch ( error => res . status ( 500 ) . json ( { message : error . message } ) ) ;
2989 } ;
3090} ;
0 commit comments