@simitgroup/simpleapp-generator 2.0.0-u-alpha → 2.0.0-v-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (66) hide show
  1. package/ReleaseNote.md +4 -0
  2. package/dist/buildinschemas/autoincreament.js +1 -1
  3. package/dist/buildinschemas/docnoformat.js +1 -1
  4. package/dist/buildinschemas/docnoformat.js.map +1 -1
  5. package/dist/buildinschemas/documentevent.js +1 -1
  6. package/dist/buildinschemas/message.d.ts +3 -0
  7. package/dist/buildinschemas/message.d.ts.map +1 -0
  8. package/dist/buildinschemas/message.js +34 -0
  9. package/dist/buildinschemas/message.js.map +1 -0
  10. package/dist/buildinschemas/webhookhistory.d.ts +3 -0
  11. package/dist/buildinschemas/webhookhistory.d.ts.map +1 -0
  12. package/dist/buildinschemas/webhookhistory.js +44 -0
  13. package/dist/buildinschemas/webhookhistory.js.map +1 -0
  14. package/dist/createproject.js +138 -0
  15. package/dist/createproject.js.map +1 -0
  16. package/dist/generate-allow-changebackend.js +305 -0
  17. package/dist/generate-allow-changebackend.js.map +1 -0
  18. package/dist/index2.js +118 -0
  19. package/dist/index2.js.map +1 -0
  20. package/dist/installdependency.js +20 -0
  21. package/dist/installdependency.js.map +1 -0
  22. package/dist/installnest.js +2 -0
  23. package/dist/installnest.js.map +1 -0
  24. package/dist/installnuxt.js +2 -0
  25. package/dist/installnuxt.js.map +1 -0
  26. package/dist/processors/groupsbuilder.js +2 -0
  27. package/dist/processors/groupsbuilder.js.map +1 -0
  28. package/dist/schematype/baseschema.js +25 -0
  29. package/dist/schematype/baseschema.js.map +1 -0
  30. package/dist/schematype/default.js +2 -0
  31. package/dist/schematype/default.js.map +1 -0
  32. package/dist/schematype/index.js +12 -0
  33. package/dist/schematype/index.js.map +1 -0
  34. package/dist/schematype/primarymasterdata.js +38 -0
  35. package/dist/schematype/primarymasterdata.js.map +1 -0
  36. package/dist/schematype/simple.js +24 -0
  37. package/dist/schematype/simple.js.map +1 -0
  38. package/dist/schematype/simplemasterdata.js +31 -0
  39. package/dist/schematype/simplemasterdata.js.map +1 -0
  40. package/dist/schematype/transaction.js +74 -0
  41. package/dist/schematype/transaction.js.map +1 -0
  42. package/package.json +1 -1
  43. package/templates/basic/miniApi/resource.controller.ts.eta +14 -0
  44. package/templates/basic/miniApi/resource.service.ts.eta +6 -0
  45. package/templates/basic/nest/controller.ts.eta +70 -76
  46. package/templates/basic/nuxt/pages.form.vue.eta +2 -2
  47. package/templates/basic/nuxt/pages.landing.vue.eta +2 -2
  48. package/templates/nest/src/main.ts._eta +14 -19
  49. package/templates/nest/src/simple-app/_core/features/user-context/user.context.ts.eta +1 -4
  50. package/templates/nest/src/simple-app/_core/framework/base/simple-app.controller.ts.eta +12 -2
  51. package/templates/nuxt/components/simpleApp/SimpleAppFormToolBar.vue._eta +1 -1
  52. package/templates/nuxt/server/api/[xorg]/[...].ts._eta +76 -121
  53. package/templates/nest/src/simple-app/features/print/api/.gitignore.eta +0 -4
  54. package/templates/nest/src/simple-app/features/print/api/.npmignore.eta +0 -1
  55. package/templates/nest/src/simple-app/features/print/api/.openapi-generator/FILES.eta +0 -8
  56. package/templates/nest/src/simple-app/features/print/api/.openapi-generator/VERSION.eta +0 -1
  57. package/templates/nest/src/simple-app/features/print/api/.openapi-generator-ignore.eta +0 -23
  58. package/templates/nest/src/simple-app/features/print/api/api.ts.eta +0 -223
  59. package/templates/nest/src/simple-app/features/print/api/base.ts.eta +0 -86
  60. package/templates/nest/src/simple-app/features/print/api/common.ts.eta +0 -150
  61. package/templates/nest/src/simple-app/features/print/api/configuration.ts.eta +0 -110
  62. package/templates/nest/src/simple-app/features/print/api/git_push.sh.eta +0 -57
  63. package/templates/nest/src/simple-app/features/print/api/index.ts.eta +0 -18
  64. package/templates/nest/src/simple-app/features/print/api/openapitools.json.eta +0 -7
  65. package/templates/nest/src/simple-app/features/print/print.module.ts.eta +0 -15
  66. package/templates/nest/src/simple-app/features/print/print.service.ts.eta +0 -41
@@ -81,52 +81,6 @@ export class <%= it.typename %>Controller extends SimpleAppController<
81
81
  async runDefault(@AppUser() appuser: UserContext) {
82
82
  return await this.service.runDefault(appuser)
83
83
  }
84
- //autocomplete shall above :id
85
- @Post('/autocomplete')
86
- <%if(superadmindoctype.includes(it.doctype)){%>
87
- @Roles(Role.SuperAdmin,Role.<%= `${it.typename}_search`%>)
88
- <%}else{%>
89
- @Roles(Role.SuperAdmin,Role.SuperUser,Role.User)
90
- <%}%>
91
- @ApiResponse({
92
- status: 200,
93
- description: 'Found',
94
- type: schemas.<%= it.typename %>AutoComplete,
95
- isArray: true,
96
- })
97
- @ApiResponse({ status: 500, description: 'Internal error' })
98
- @ApiQuery({ name: 'keyword', type:String})
99
- @ApiBody({ description: 'Data', type: ()=>Object})
100
- @ApiOperation({ operationId: 'autoComplete',description:"retrieve array of {_id, code, name}" })
101
- <%~ drawMiniAppScope('autoComplete') %>
102
- async autoComplete(@AppUser() appuser: UserContext,
103
- @Query('keyword') keyword:string,
104
- @Body() data: schemas.<%=it.typename%>,
105
- ) {
106
- return this._autocomplete(appuser, keyword,data);
107
- }
108
-
109
-
110
-
111
- @Post()
112
- <%if(superadmindoctype.includes(it.doctype)){%>
113
- @Roles(Role.SuperAdmin,Role.<%= `${it.typename}_create`%>)
114
- <%}else{%>
115
- @Roles(Role.SuperAdmin,Role.SuperUser,Role.<%= `${it.typename}_create`%>)
116
- <%}%>
117
- @ApiResponse({
118
- status: 201,
119
- description: 'success',
120
- type: schemas.<%= it.typename%>
121
- })
122
- @ApiResponse({ status: 400, description: 'bad request' })
123
- @ApiResponse({ status: 500, description: 'internal error' })
124
- @ApiBody({ description: 'Data',type:schemas.<%= it.typename%> })
125
- @ApiOperation({ operationId: 'runCreate' })
126
- <%~ drawMiniAppScope('create') %>
127
- async create(@AppUser() appuser: UserContext,@Body() data: schemas.<%= it.typename%>) {
128
- return await this._create(appuser,data)
129
- }
130
84
 
131
85
  @Post('/search')
132
86
  @HttpCode(200)
@@ -149,7 +103,6 @@ export class <%= it.typename %>Controller extends SimpleAppController<
149
103
  return await this._search(appuser,data)
150
104
  }
151
105
 
152
-
153
106
  <% if(simpleappconfig.search !==undefined){%>
154
107
  @Post('/fulltextsearch')
155
108
  @HttpCode(200)
@@ -171,33 +124,6 @@ export class <%= it.typename %>Controller extends SimpleAppController<
171
124
  }
172
125
  <%}%>
173
126
 
174
-
175
- @Patch('bulk-patch')
176
- @ApiResponse({ status: 200, description: 'success',})
177
- @Roles(Role.SuperAdmin, Role.SuperUser, Role.<%= it.typename%>_update)
178
- @ApiResponse({ status: 404, description: 'Document not found' })
179
- @ApiResponse({ status: 500, description: 'Internal error' })
180
- @ApiBody({ description: 'Data', type: schemas.PatchManyRequest<schemas.<%= it.typename%>> })
181
- @ApiOperation({ operationId: 'runPatchMany' })
182
- <%~ drawMiniAppScope('patch-many') %>
183
- async patchMany(@AppUser() appuser: UserContext, @Param('id') id: string, @Body() patchManyData: schemas.PatchManyRequest<schemas.<%= it.typename%>>) {
184
- return await this._patchMany(appuser, id, patchManyData);
185
- }
186
-
187
-
188
- /***************************** start status control api definitions *****************************************/
189
- <%for(let s=0; s<it.docStatusSettings.length; s++){ %>
190
- <%let statusconf = it.docStatusSettings[s]%>
191
- <%let statusname = statusconf['status']%>
192
- @Post(':id/set-<%=statusname%>')
193
- @ApiBody({ description: 'Document data', type: Object })
194
- @Roles(Role.SuperAdmin,Role.<%= `${it.typename}_${statusname}`%>)
195
- async setStatus<%=capitalizeFirstLetter(statusname)%>(@AppUser() appuser: UserContext,@Param('id') id: string, @Body() data:any,){
196
- return await this.service.setDocumentStatus(appuser,id,data,'<%=statusname%>',)
197
- }
198
- <%}%>
199
- /***************************** end status control api definitions *****************************************/
200
-
201
127
  @Get(':id')
202
128
  <%if(superadmindoctype.includes(it.doctype)){%>
203
129
  @Roles(Role.SuperAdmin,Role.<%= `${it.typename}_search`%>)
@@ -221,8 +147,52 @@ export class <%= it.typename %>Controller extends SimpleAppController<
221
147
  return data
222
148
  }
223
149
  }
224
-
225
150
 
151
+ //autocomplete shall above :id
152
+ @Post('/autocomplete')
153
+ <%if(superadmindoctype.includes(it.doctype)){%>
154
+ @Roles(Role.SuperAdmin,Role.<%= `${it.typename}_search`%>)
155
+ <%}else{%>
156
+ @Roles(Role.SuperAdmin,Role.SuperUser,Role.User)
157
+ <%}%>
158
+ @ApiResponse({
159
+ status: 200,
160
+ description: 'Found',
161
+ type: schemas.<%= it.typename %>AutoComplete,
162
+ isArray: true,
163
+ })
164
+ @ApiResponse({ status: 500, description: 'Internal error' })
165
+ @ApiQuery({ name: 'keyword', type:String})
166
+ @ApiBody({ description: 'Data', type: ()=>Object})
167
+ @ApiOperation({ operationId: 'autoComplete',description:"retrieve array of {_id, code, name}" })
168
+ <%~ drawMiniAppScope('autoComplete') %>
169
+ async autoComplete(@AppUser() appuser: UserContext,
170
+ @Query('keyword') keyword:string,
171
+ @Body() data: schemas.<%=it.typename%>,
172
+ ) {
173
+ return this._autocomplete(appuser, keyword,data);
174
+ }
175
+
176
+ @Post()
177
+ <%if(superadmindoctype.includes(it.doctype)){%>
178
+ @Roles(Role.SuperAdmin,Role.<%= `${it.typename}_create`%>)
179
+ <%}else{%>
180
+ @Roles(Role.SuperAdmin,Role.SuperUser,Role.<%= `${it.typename}_create`%>)
181
+ <%}%>
182
+ @ApiResponse({
183
+ status: 201,
184
+ description: 'success',
185
+ type: schemas.<%= it.typename%>
186
+ })
187
+ @ApiResponse({ status: 400, description: 'bad request' })
188
+ @ApiResponse({ status: 500, description: 'internal error' })
189
+ @ApiBody({ description: 'Data',type:schemas.<%= it.typename%> })
190
+ @ApiOperation({ operationId: 'runCreate' })
191
+ <%~ drawMiniAppScope('create') %>
192
+ async create(@AppUser() appuser: UserContext,@Body() data: schemas.<%= it.typename%>) {
193
+ return await this._create(appuser,data)
194
+ }
195
+
226
196
  @Put(':id')
227
197
  @ApiResponse({
228
198
  status: 200,
@@ -241,6 +211,7 @@ export class <%= it.typename %>Controller extends SimpleAppController<
241
211
  async update(@AppUser() appuser: UserContext,@Param('id') id: string, @Body() data: schemas.<%= it.typename%>) {
242
212
  return await this._update(appuser,id, data) ;
243
213
  }
214
+
244
215
  @Patch(':id')
245
216
  @ApiResponse({
246
217
  status: 200,
@@ -260,6 +231,18 @@ export class <%= it.typename %>Controller extends SimpleAppController<
260
231
  return await this._patch(appuser,id, data) ;
261
232
  }
262
233
 
234
+ @Patch('bulk-patch')
235
+ @ApiResponse({ status: 200, description: 'success', type: schemas.UpdateManyResponse})
236
+ @Roles(Role.SuperAdmin, Role.SuperUser, Role.<%= it.typename%>_update)
237
+ @ApiResponse({ status: 404, description: 'Document not found' })
238
+ @ApiResponse({ status: 500, description: 'Internal error' })
239
+ @ApiBody({ description: 'Data', type: schemas.PatchManyRequest<schemas.<%= it.typename%>> })
240
+ @ApiOperation({ operationId: 'runPatchMany' })
241
+ <%~ drawMiniAppScope('patch-many') %>
242
+ async patchMany(@AppUser() appuser: UserContext, @Body() patchManyData: schemas.PatchManyRequest<schemas.<%= it.typename%>>) {
243
+ return await this._patchMany(appuser, patchManyData);
244
+ }
245
+
263
246
  @Delete(':id')
264
247
  <%if(superadmindoctype.includes(it.doctype)){%>
265
248
  @Roles(Role.SuperAdmin,Role.<%= `${it.typename}_delete`%>)
@@ -279,6 +262,17 @@ export class <%= it.typename %>Controller extends SimpleAppController<
279
262
  return this._delete(appuser,id);
280
263
  }
281
264
 
282
-
265
+ /***************************** start status control api definitions *****************************************/
266
+ <%for(let s=0; s<it.docStatusSettings.length; s++){ %>
267
+ <%let statusconf = it.docStatusSettings[s]%>
268
+ <%let statusname = statusconf['status']%>
269
+ @Post(':id/set-<%=statusname%>')
270
+ @ApiBody({ description: 'Document data', type: Object })
271
+ @Roles(Role.SuperAdmin,Role.<%= `${it.typename}_${statusname}`%>)
272
+ async setStatus<%=capitalizeFirstLetter(statusname)%>(@AppUser() appuser: UserContext,@Param('id') id: string, @Body() data:any,){
273
+ return await this.service.setDocumentStatus(appuser,id,data,'<%=statusname%>',)
274
+ }
275
+ <%}%>
276
+ /***************************** end status control api definitions *****************************************/
283
277
 
284
278
  }
@@ -146,10 +146,10 @@
146
146
  */
147
147
  import { SimpleAppInputType,FormCrudEvent } from "~/types";
148
148
  import { <%= it.typename %> } from "~/simpleapp/generate/types";
149
- import { <%= it.typename %>Doc} from "~/simpleapp/docs/<%= capitalizeFirstLetter(it.name) %>Doc"
149
+ import { <%= capitalizeFirstLetter(it.name) %>Doc} from "~/simpleapp/docs/<%= capitalizeFirstLetter(it.name) %>Doc"
150
150
 
151
151
 
152
- const props = defineProps<{ _id?: string, doc?: <%= it.typename %>Doc , paras?:<%= it.typename %>}>();
152
+ const props = defineProps<{ _id?: string, doc?: <%= capitalizeFirstLetter(it.name) %>Doc , paras?:<%= it.typename %>}>();
153
153
  const doc = props.doc ?? useNuxtApp().$<%= capitalizeFirstLetter(it.name) %>Doc()
154
154
  const data = doc.getReactiveData();
155
155
  const emits = defineEmits(["after"]);
@@ -19,8 +19,8 @@
19
19
  import { <%= it.typename %> } from '~/simpleapp/generate/openapi';
20
20
 
21
21
 
22
- const {$<%= it.typename %>Doc,$listen } = useNuxtApp();
23
- const doc = $<%= it.typename %>Doc()
22
+ const {$<%= capitalizeFirstLetter(it.name) %>Doc,$listen } = useNuxtApp();
23
+ const doc = $<%= capitalizeFirstLetter(it.name) %>Doc()
24
24
  const docdata = doc.getReactiveData();
25
25
  type <%= it.typename %>Key = keyof <%= it.typename %>
26
26
 
@@ -1,18 +1,9 @@
1
- /**
2
- * This file was automatically generated by simpleapp generator. It is changable.
3
- * --remove-this-line-to-prevent-override--
4
- * last change 2023-10-28
5
- * Author: Ks Tan
6
- */
7
-
8
- import { NestFactory } from '@nestjs/core';
9
- import { AppModule } from './app.module';
10
- import { SimpleAppExceptionFilter } from './simple-app/_core/framework/exception-filter';
11
- import { HttpAdapterHost } from '@nestjs/core';
12
- import {generatorVersion} from 'src/simple-app/_core/framework/generator-version'
13
- import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger';
14
- import { writeFileSync } from 'fs';
15
1
  import { LogLevel } from '@nestjs/common';
2
+ import { HttpAdapterHost, NestFactory } from '@nestjs/core';
3
+ import { DocumentBuilder, SwaggerModule } from '@nestjs/swagger';
4
+ import { writeFileSync } from 'fs';
5
+ import { generatorVersion } from 'src/simple-app/_core/framework/generator-version';
6
+ import { AppModule } from './app.module';
16
7
  const yaml = require('yaml');
17
8
 
18
9
  async function bootstrap() {
@@ -21,15 +12,19 @@ async function bootstrap() {
21
12
  logger: logs,
22
13
  });
23
14
 
15
+ // Handle shutdown signals for docker / kubernetes
16
+ app.enableShutdownHooks();
17
+
24
18
  // app.enableCors();
25
19
  const httpAdapter = app.get(HttpAdapterHost);
26
20
  // app.useGlobalFilters(new SimpleAppExceptionFilter(httpAdapter));
27
21
 
28
22
  const config = new DocumentBuilder()
29
- .setTitle(process.env.PROJECT_NAME)
23
+ .setTitle('simtrain-eco backend api')
30
24
  .addServer(process.env.APP_SWAGGER_SERVER_URL)
31
- .setDescription(`${process.env.PROJECT_DESCRIPTION} (generator: ${generatorVersion})`)
32
- .setVersion(process.env.PROJECT_VERSION)
25
+ .setDescription(`Internal use only (generator: ${generatorVersion})`)
26
+ .setVersion('2.0')
27
+
33
28
  .addApiKey(
34
29
  {
35
30
  in: 'header',
@@ -54,7 +49,7 @@ async function bootstrap() {
54
49
  .addApiKey(
55
50
  {
56
51
  in: 'header',
57
- name: 'x-api-key',
52
+ name: 'x-apikey',
58
53
  type: 'apiKey',
59
54
  description: 'optional only use for specal case',
60
55
  },
@@ -63,7 +58,7 @@ async function bootstrap() {
63
58
  .addApiKey(
64
59
  {
65
60
  in: 'header',
66
- name: 'x-api-secret',
61
+ name: 'x-apisecret',
67
62
  type: 'apiKey',
68
63
  description: 'optional only use for specal case',
69
64
  },
@@ -1150,10 +1150,7 @@ export class UserContext extends UserContextInfo {
1150
1150
  return data;
1151
1151
  }
1152
1152
 
1153
- isOnlyExecutive = () => {
1154
- return this.groups.includes(Role.Executive) && this.groups.length == 1;
1155
- };
1156
-
1153
+
1157
1154
  offsetDate(date: string): string {
1158
1155
  const timestamp = new Date(date).getTime();
1159
1156
  const offsets = this.getOffsetMinute() * 60000;
@@ -8,7 +8,10 @@ import { Controller, Get, Put, Post, Delete, Body, Param, Type } from '@nestjs/c
8
8
  // import { ApiTags, ApiBody, ApiResponse, ApiOperation } from '@nestjs/swagger';
9
9
  import { UserContext } from '../../features/user-context/user.context';
10
10
  import { SearchBody, TextSearchBody,PatchManyRequest } from '../schemas';
11
+ import { UpdateWriteOpResult } from 'mongoose';
12
+
11
13
  const doctype = 'person'.toUpperCase();
14
+
12
15
  type ServiceType = {
13
16
  list: Function;
14
17
  search: Function;
@@ -22,6 +25,7 @@ type ServiceType = {
22
25
  setData: Function;
23
26
  getAutoComplete: Function;
24
27
  fullTextSearch: Function;
28
+ patchMany: Function;
25
29
  };
26
30
 
27
31
  // @ApiTags(doctype)
@@ -38,15 +42,19 @@ export class SimpleAppController<TService extends ServiceType, TApiSchema> {
38
42
  async _list(appuser: UserContext) {
39
43
  return this.service.list(appuser);
40
44
  }
45
+
41
46
  async _fulltextsearch(appuser: UserContext, body: TextSearchBody) {
42
47
  return this.service.fullTextSearch(appuser, body);
43
48
  }
49
+
44
50
  async _search(appuser: UserContext, searchObject: SearchBody) {
45
51
  return this.service.search(appuser, searchObject['filter'], searchObject['fields'], searchObject['sorts'], searchObject['lookup']);
46
52
  }
53
+
47
54
  async _autocomplete(appuser: UserContext, keyword: string, data?: TApiSchema) {
48
55
  return this.service.getAutoComplete(appuser, keyword, data);
49
56
  }
57
+
50
58
  async _findOne(appuser: UserContext, id: string) {
51
59
  const result = (await this.service.findById(appuser, id)) as TApiSchema;
52
60
 
@@ -65,6 +73,7 @@ export class SimpleAppController<TService extends ServiceType, TApiSchema> {
65
73
  Object.assign(newdata, data); //
66
74
  return this.service.findIdThenUpdate(appuser, id, newdata) as TApiSchema;
67
75
  }
76
+
68
77
  async _patch(appuser: UserContext, id: string, data: TApiSchema) {
69
78
  const newdata: TApiSchema = {} as TApiSchema; //= { ...data };
70
79
  Object.assign(newdata, data); //
@@ -74,8 +83,9 @@ export class SimpleAppController<TService extends ServiceType, TApiSchema> {
74
83
  async _delete(appuser: UserContext, id: string) {
75
84
  return this.service.findIdThenDelete(appuser, id);
76
85
  }
77
- async _patchMany(appuser: UserContext, id: string, patchManyData: PatchManyRequest<TApiSchema>) {
78
- return this.service.findIdThenPatch(appuser, id, patchManyData) as TApiSchema;
86
+
87
+ async _patchMany(appuser: UserContext, patchManyData: PatchManyRequest<TApiSchema>) {
88
+ return this.service.findIdThenPatch(appuser, patchManyData);
79
89
  }
80
90
 
81
91
  async _deleteMany(appuser: UserContext, data: SearchBody) {
@@ -48,7 +48,7 @@
48
48
  <div v-if="menu.label && menu.type == 'crud'">
49
49
  <ButtonAction
50
50
  v-if="menu.action == 'print'"
51
- :disabled="!canPerform(doc.getDocName(true), 'access')"
51
+ :disabled="!canPerform(doc.getDocName(true), 'print')"
52
52
  @click="emitEvent(menu, $event)"
53
53
  :action-name="menu.action"
54
54
  >{{ menu.label }}</ButtonAction
@@ -5,128 +5,83 @@
5
5
  * Author: Ks Tan
6
6
  */
7
7
 
8
-
9
- import axios, { AxiosRequestConfig } from 'axios';
10
- import { getServerSession } from '#auth'
11
- import type { Session } from 'next-auth';
12
- import * as fs from 'fs'
13
- export default defineEventHandler(async (event:any) => {
14
- type additionalprops = {accessToken?:string}
15
- let session:any=null
16
-
17
-
18
- try {
19
- session = await getServerSession(event)
20
-
21
- } catch (error) {
22
- throw createError({ statusText: 'Unauthorized', status: 302 })
23
- }
24
- if(!session) {
25
- throw createError({ statusText: 'Unauthorized', status: 302 })
26
- }
27
-
28
- return new Promise<any>(async (resolve, reject) => {
29
- const xOrg = event.context.params?.xorg ?? ''
30
- const documentLink = event.context.params?._ ?? ''
31
- const accessToken = session?.accessToken;
32
-
8
+ import axios, { AxiosRequestConfig } from "axios";
9
+ import { getServerSession } from "#auth";
10
+ export default defineEventHandler(async (event: any) => {
11
+ let session: any = null;
12
+ try {
13
+ session = await getServerSession(event);
14
+ } catch (error) {
15
+ throw createError({ statusText: "Unauthorized", status: 302 });
16
+ }
17
+ if (!session) {
18
+ throw createError({ statusText: "Unauthorized", status: 302 });
19
+ }
33
20
 
34
- let forwardData: any = {};
35
- const req = event.node.req;
36
- let bodydata: any
37
- let querydata:any
38
- querydata = getQuery(event);
39
- if(req.method == 'POST' || req.method == 'PUT' || req.method == 'PATCH' ) {
40
- bodydata = await readBody(event);
41
- }
21
+ return new Promise<any>(async (resolve, reject) => {
22
+ const xOrg = event.context.params?.xorg ?? "";
23
+ const documentLink = event.context.params?._ ?? "";
24
+ const accessToken = session?.accessToken;
25
+ const req = event.node.req;
26
+ let bodydata: any;
27
+ let querydata: any;
28
+ querydata = getQuery(event);
29
+ if (req.method == "POST" || req.method == "PUT" || req.method == "PATCH") {
30
+ bodydata = await readBody(event);
31
+ }
42
32
 
33
+ const frontEndRes = event.node.res;
34
+ const url = process.env.SIMPLEAPP_BACKEND_URL + "/" + documentLink;
35
+ const axiosConfig: AxiosRequestConfig = {
36
+ method: req.method,
37
+ url: url,
38
+ headers: {
39
+ Authorization: `Bearer ${accessToken}`,
40
+ "X-Org": xOrg,
41
+ "X-Mini-App-Code": event.headers.get("x-mini-app-code"),
42
+ "x-mini-app-dev-portal-app-id": event.headers.get(
43
+ "x-mini-app-dev-portal-app-id",
44
+ ),
45
+ },
46
+ data: bodydata,
47
+ params: querydata,
48
+ };
43
49
 
44
- const frontEndRes = event.node.res;
45
- const url = process.env.SIMPLEAPP_BACKEND_URL + '/' + documentLink;
46
- const axiosConfig: AxiosRequestConfig = {
47
- method: req.method,
48
- url: url,
49
- headers: {
50
- Authorization: `Bearer ${accessToken}`,
51
- 'X-Org': xOrg,
52
- },
53
- data: bodydata,
54
- params: querydata,
55
- }
56
-
57
- try{
58
- const res = await axios(axiosConfig)
59
- if (res.headers['content-type'] === 'image/png') {
60
- frontEndRes.setHeader('Content-Type', 'image/png');
61
- frontEndRes.setHeader('Content-Disposition', 'inline');
62
- frontEndRes.end(Buffer.from(res.data, 'binary'));
63
- }else if(documentLink.includes('images/')){
64
- // console.log(documentLink," Resdata of base64 photo",res.data.length)
65
- let imageData
66
- frontEndRes.setHeader('Content-Type', 'image/png');
67
-
68
- // console.log("load image for",documentLink)
69
- if( res.data.length){
70
- console.log("obtain base64 from server length:",res.data.length)
71
- imageData = base64ToBuffer(res.data);
72
-
73
- }else{
74
- // console.log("server no image, use default image")
75
- const folder = 'assets/images/'
76
- let filename = filename='unknown.png';
77
- const fullpath = folder+filename;
78
- if(fs.existsSync(fullpath)){
79
- imageData = fs.readFileSync(fullpath)
80
- }else{
81
- console.log(fullpath,'does not exists')
82
- }
83
- }
84
- frontEndRes.end(Buffer.from(imageData, 'binary'));
85
-
86
- }else{
87
- frontEndRes.statusCode = res.status;
88
- if(res.statusText) {
89
- frontEndRes.statusMessage = res.statusText;
90
- }
91
- resolve(res.data);
92
- }
93
- }catch(error){
94
- if(!error?.response){
95
- console.log("backend server no response ",error.code)
96
- reject({
97
- statusMessage:"backendServerDownMessage",
98
- statusCode: 503,
99
- });
100
- }else if (error.response.status == 401) {
101
- return sendRedirect(event, '/login', 302)
102
- }else{
103
- const responseCode = error.response.data?.statusCode ? error.response.data.statusCode : error.response.status
104
- const responseMsg = error.response.data ? error.response.data.message : error.response.statusText
105
- // reject(error.data)
106
- // console.log("----error.response.data--",responseMsg,error.response.data,error.response.status,responseCode)
107
- reject({
108
- statusMessage: responseMsg,
109
- statusCode: responseCode ,
110
- data: error.response.data
111
- });
112
-
113
- }
50
+ try {
51
+ const res = await axios(axiosConfig);
52
+ for(const k of Object.keys(res.headers)){
53
+ frontEndRes.setHeader[k]=res.headers[k]
54
+ }
55
+ frontEndRes.statusCode = res.status;
56
+ if (res.statusText) {
57
+ frontEndRes.statusMessage = res.statusText;
114
58
  }
115
- })
116
-
117
- })
118
-
119
-
120
-
121
- function base64ToBuffer(base64String:string) {
122
- // Split the base64 string into parts
123
- const parts = base64String.split(',');
124
- const contentType = parts[0].split(':')[1];
125
- const base64Data = parts[1];
126
-
127
- // Decode the base64 data
128
- const binaryString = atob(base64Data);
129
- const buffer = new Buffer.from(binaryString, 'binary');
130
-
131
- return buffer
132
- }
59
+ resolve(res.data);
60
+ } catch (error:any) {
61
+ console.log("Axios error", error.code, error);
62
+ if (!error?.response) {
63
+ console.log("backend server no response ", error.code);
64
+ reject({
65
+ statusMessage: "backendServerDownMessage",
66
+ statusCode: 503,
67
+ });
68
+ } else if (error.response.status == 401) {
69
+ return sendRedirect(event, "/login", 302);
70
+ } else {
71
+ const responseCode = error.response.data?.statusCode
72
+ ? error.response.data.statusCode
73
+ : error.response.status;
74
+ const responseMsg = error.response.data
75
+ ? error.response.data.message
76
+ : error.response.statusText;
77
+ // reject(error.data)
78
+ // console.log("----error.response.data--",responseMsg,error.response.data,error.response.status,responseCode)
79
+ reject({
80
+ statusMessage: responseMsg,
81
+ statusCode: responseCode,
82
+ data: error.response.data,
83
+ });
84
+ }
85
+ }
86
+ });
87
+ });
@@ -1,4 +0,0 @@
1
- wwwroot/*.js
2
- node_modules
3
- typings
4
- dist
@@ -1 +0,0 @@
1
- # empty npmignore to ensure all required files (e.g., in the dist folder) are published by npm
@@ -1,8 +0,0 @@
1
- .gitignore
2
- .npmignore
3
- api.ts
4
- base.ts
5
- common.ts
6
- configuration.ts
7
- git_push.sh
8
- index.ts
@@ -1,23 +0,0 @@
1
- # OpenAPI Generator Ignore
2
- # Generated by openapi-generator https://github.com/openapitools/openapi-generator
3
-
4
- # Use this file to prevent files from being overwritten by the generator.
5
- # The patterns follow closely to .gitignore or .dockerignore.
6
-
7
- # As an example, the C# client generator defines ApiClient.cs.
8
- # You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:
9
- #ApiClient.cs
10
-
11
- # You can match any string of characters against a directory, file or extension with a single asterisk (*):
12
- #foo/*/qux
13
- # The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux
14
-
15
- # You can recursively match patterns against a directory, file or extension with a double asterisk (**):
16
- #foo/**/qux
17
- # This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux
18
-
19
- # You can also negate patterns with an exclamation (!).
20
- # For example, you can ignore all files in a docs folder with the file extension .md:
21
- #docs/*.md
22
- # Then explicitly reverse the ignore rule for a single file:
23
- #!docs/README.md