adminforth 2.13.0-next.47 → 2.13.0-next.49

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.
@@ -1,1469 +0,0 @@
1
- /// <reference types="node" resolution-mode="require"/>
2
- import type { Express, Request } from 'express';
3
- import type { Writable } from 'stream';
4
- import { ActionCheckSource, AdminForthFilterOperators, AdminForthSortDirections, AllowedActionsEnum, type AdminForthComponentDeclaration, type AdminUser, type AllowedActionsResolved, type AdminForthBulkActionCommon, type AdminForthForeignResourceCommon, type AdminForthResourceColumnCommon, type AdminForthResourceInputCommon, type AdminForthComponentDeclarationFull, type AdminForthConfigMenuItem, type AnnouncementBadgeResponse, AdminForthResourcePages, type AdminForthResourceColumnInputCommon } from './Common.js';
5
- export interface ICodeInjector {
6
- srcFoldersToSync: Object;
7
- allComponentNames: Object;
8
- devServerPort: number;
9
- getServeDir(): string;
10
- registerCustomComponent(filePath: string): void;
11
- spaTmpPath(): string;
12
- }
13
- export interface IConfigValidator {
14
- validateConfig(): void;
15
- validateAfterPluginsActivation(): void;
16
- postProcessAfterDiscover(resource: AdminForthResource): void;
17
- }
18
- export interface IAdminForthHttpResponse {
19
- setHeader: (key: string, value: string) => void;
20
- setStatus: (code: number, message: string) => void;
21
- blobStream: () => Writable;
22
- }
23
- /**
24
- * Implement this interface to create custom HTTP server adapter for AdminForth.
25
- */
26
- export interface IHttpServer {
27
- /**
28
- * Sets up HTTP server to serve AdminForth SPA.
29
- * if hotReload is true, it should proxy all requests and headers to Vite dev server at `http://localhost:5173$\{req.url\}`
30
- * otherwise it should serve AdminForth SPA from dist folder. See Express for example.
31
- */
32
- setupSpaServer(): void;
33
- /**
34
- * Method which should register endpoint in HTTP server.
35
- *
36
- * @param options : Object with method, path and handler properties.
37
- */
38
- endpoint(options: {
39
- method: string;
40
- noAuth?: boolean;
41
- path: string;
42
- handler: (body: any, adminUser: any, query: {
43
- [key: string]: string;
44
- }, headers: {
45
- [key: string]: string;
46
- }, cookies: {
47
- [key: string]: string;
48
- }, response: IAdminForthHttpResponse) => void;
49
- }): void;
50
- }
51
- export interface IExpressHttpServer extends IHttpServer {
52
- /**
53
- * Call this method to serve AdminForth SPA from Express instance.
54
- * @param app : Express instance
55
- */
56
- serve(app: Express): void;
57
- /**
58
- * Method to start listening on port.
59
- */
60
- listen(port: number, callback: Function): void;
61
- listen(port: number, host: string, callback: Function): void;
62
- /**
63
- * Method (middleware) to wrap express endpoints with authorization check.
64
- * Adds adminUser to request object if user is authorized. Drops request with 401 status if user is not authorized.
65
- * @param callable : Function which will be called if user is authorized.
66
- *
67
- *
68
- * @example
69
- * ```ts
70
- * expressApp.get('/myApi', authorize((req, res) => {
71
- * console.log('User is authorized', req.adminUser);
72
- * res.json({ message: 'Hello World' });
73
- * }));
74
- * ```
75
- *
76
- */
77
- authorize(callable: Function): void;
78
- }
79
- export interface ITranslateFunction {
80
- (msg: string, category: string, params: any, pluralizationNumber?: number): Promise<string>;
81
- }
82
- export interface IAdminUserExpressRequest extends Omit<Request, 'protocol' | 'param' | 'unshift'> {
83
- adminUser: AdminUser;
84
- }
85
- export interface ITranslateExpressRequest extends Omit<Request, 'protocol' | 'param' | 'unshift'> {
86
- tr: ITranslateFunction;
87
- }
88
- export interface IAdminForthSingleFilter {
89
- field?: string;
90
- operator?: AdminForthFilterOperators.EQ | AdminForthFilterOperators.NE | AdminForthFilterOperators.GT | AdminForthFilterOperators.LT | AdminForthFilterOperators.GTE | AdminForthFilterOperators.LTE | AdminForthFilterOperators.LIKE | AdminForthFilterOperators.ILIKE | AdminForthFilterOperators.IN | AdminForthFilterOperators.NIN;
91
- value?: any;
92
- rightField?: string;
93
- insecureRawSQL?: string;
94
- insecureRawNoSQL?: any;
95
- }
96
- export interface IAdminForthAndOrFilter {
97
- operator: AdminForthFilterOperators.AND | AdminForthFilterOperators.OR;
98
- subFilters: Array<IAdminForthAndOrFilter | IAdminForthSingleFilter>;
99
- }
100
- export interface IAdminForthSort {
101
- field: string;
102
- direction: AdminForthSortDirections;
103
- }
104
- export interface IAdminForthDataSourceConnector {
105
- client: any;
106
- /**
107
- * Function to setup client connection to database.
108
- * @param url URL to database. Examples: clickhouse://demo:demo@localhost:8125/demo
109
- */
110
- setupClient(url: string): Promise<void>;
111
- /**
112
- * Function to get all tables from database.
113
- */
114
- getAllTables(): Promise<Array<string>>;
115
- /**
116
- * Function to get all columns in table.
117
- */
118
- getAllColumnsInTable(tableName: string): Promise<Array<{
119
- name: string;
120
- type?: string;
121
- isPrimaryKey?: boolean;
122
- sampleValue?: any;
123
- }>>;
124
- /**
125
- * Optional.
126
- * You an redefine this function to define how one record should be fetched from database.
127
- * You you will not redefine it, AdminForth will use {@link IAdminForthDataSourceConnector.getData} with limit 1 and offset 0 and
128
- * filter by primary key.
129
- */
130
- getRecordByPrimaryKeyWithOriginalTypes(resource: AdminForthResource, recordId: string): Promise<any>;
131
- /**
132
- * Function should go over all columns of table defined in resource.table and try to guess
133
- * data and constraints for each columns.
134
- * Type should be saved to:
135
- * - {@link AdminForthResourceColumn.type}
136
- * Constraints:
137
- * - {@link AdminForthResourceColumn.required}
138
- * - {@link AdminForthResourceColumn.primaryKey}
139
- * For string fields:
140
- * - {@link AdminForthResourceColumn.maxLength}
141
- * For numbers:
142
- * - {@link AdminForthResourceColumn.min}
143
- * - {@link AdminForthResourceColumn.max}
144
- * - {@link AdminForthResourceColumn.minValue}, {@link AdminForthResourceColumn.maxValue}, {@link AdminForthResourceColumn.enum}, {@link AdminForthResourceColumn.foreignResource}, {@link AdminForthResourceColumn.sortable}, {@link AdminForthResourceColumn.backendOnly}, {@link AdminForthResourceColumn.masked}, {@link AdminForthResourceColumn.virtual}, {@link AdminForthResourceColumn.components}, {@link AdminForthResourceColumn.allowMinMaxQuery}, {@link AdminForthResourceColumn.editingNote}, {@link AdminForthResourceColumn.showIn}, {@link AdminForthResourceColumn.isUnique}, {@link AdminForthResourceColumn.validation})
145
- * Also you can additionally save original column type to {@link AdminForthResourceColumn._underlineType}. This might be later used
146
- * in {@link IAdminForthDataSourceConnector.getFieldValue} and {@link IAdminForthDataSourceConnector.setFieldValue} methods.
147
- *
148
- *
149
- * @param resource
150
- */
151
- discoverFields(resource: AdminForthResource): Promise<{
152
- [key: string]: AdminForthResourceColumn;
153
- }>;
154
- /**
155
- * Used to transform record after fetching from database.
156
- * According to AdminForth convention, if {@link AdminForthResourceColumn.type} is set to {@link AdminForthDataTypes.DATETIME} then it should be transformed to ISO string.
157
- * @param field
158
- * @param value
159
- */
160
- getFieldValue(field: AdminForthResourceColumn, value: any): any;
161
- /**
162
- * Used to transform record before saving to database. Should perform operation inverse to {@link IAdminForthDataSourceConnector.getFieldValue}
163
- * @param field
164
- * @param value
165
- */
166
- setFieldValue(field: AdminForthResourceColumn, value: any): any;
167
- /**
168
- * Used to fetch data from database.
169
- * This method is reused both to list records and show one record (by passing limit 1 and offset 0) .
170
- *
171
- * Fields are returned from db "as is" then {@link AdminForthBaseConnector.getData} will transform each field using {@link IAdminForthDataSourceConnector.getFieldValue}
172
- */
173
- getDataWithOriginalTypes({ resource, limit, offset, sort, filters }: {
174
- resource: AdminForthResource;
175
- limit: number;
176
- offset: number;
177
- sort: IAdminForthSort[];
178
- filters: IAdminForthAndOrFilter;
179
- }): Promise<Array<any>>;
180
- /**
181
- * Used to get count of records in database.
182
- */
183
- getCount({ resource, filters }: {
184
- resource: AdminForthResource;
185
- filters: IAdminForthAndOrFilter;
186
- }): Promise<number>;
187
- /**
188
- * Optional method which used to get min and max values for columns in resource.
189
- * Called only for columns which have {@link AdminForthResourceColumn.allowMinMaxQuery} set to true.
190
- *
191
- * Internally should call {@link IAdminForthDataSourceConnector.getFieldValue} for both min and max values.
192
- */
193
- getMinMaxForColumnsWithOriginalTypes({ resource, columns }: {
194
- resource: AdminForthResource;
195
- columns: AdminForthResourceColumn[];
196
- }): Promise<{
197
- [key: string]: {
198
- min: any;
199
- max: any;
200
- };
201
- }>;
202
- /**
203
- * Used to create record in database. Should return value of primary key column of created record.
204
- */
205
- createRecordOriginalValues({ resource, record }: {
206
- resource: AdminForthResource;
207
- record: any;
208
- }): Promise<string>;
209
- /**
210
- * Update record in database. newValues might have not all fields in record, but only changed ones.
211
- * recordId is value of field which is marked as {@link AdminForthResourceColumn.primaryKey}
212
- */
213
- updateRecordOriginalValues({ resource, recordId, newValues }: {
214
- resource: AdminForthResource;
215
- recordId: string;
216
- newValues: any;
217
- }): Promise<void>;
218
- /**
219
- * Used to delete record in database.
220
- */
221
- deleteRecord({ resource, recordId }: {
222
- resource: AdminForthResource;
223
- recordId: any;
224
- }): Promise<boolean>;
225
- }
226
- /**
227
- * Interface that exposes methods to interact with AdminForth in standard way
228
- */
229
- export interface IAdminForthDataSourceConnectorBase extends IAdminForthDataSourceConnector {
230
- validateAndNormalizeInputFilters(filter: IAdminForthSingleFilter | IAdminForthAndOrFilter | Array<IAdminForthSingleFilter | IAdminForthAndOrFilter> | undefined): IAdminForthAndOrFilter;
231
- getPrimaryKey(resource: AdminForthResource): string;
232
- getData({ resource, limit, offset, sort, filters }: {
233
- resource: AdminForthResource;
234
- limit: number;
235
- offset: number;
236
- sort: IAdminForthSort[];
237
- filters: IAdminForthAndOrFilter;
238
- getTotals?: boolean;
239
- }): Promise<{
240
- data: Array<any>;
241
- total: number;
242
- }>;
243
- getRecordByPrimaryKey(resource: AdminForthResource, recordId: string): Promise<any>;
244
- createRecord({ resource, record, adminUser }: {
245
- resource: AdminForthResource;
246
- record: any;
247
- adminUser: AdminUser;
248
- }): Promise<{
249
- ok: boolean;
250
- error?: string;
251
- createdRecord?: any;
252
- }>;
253
- updateRecord({ resource, recordId, newValues }: {
254
- resource: AdminForthResource;
255
- recordId: string;
256
- newValues: any;
257
- }): Promise<{
258
- ok: boolean;
259
- error?: string;
260
- }>;
261
- getMinMaxForColumns({ resource, columns }: {
262
- resource: AdminForthResource;
263
- columns: AdminForthResourceColumn[];
264
- }): Promise<{
265
- [key: string]: {
266
- min: any;
267
- max: any;
268
- };
269
- }>;
270
- }
271
- export interface IAdminForthDataSourceConnectorConstructor {
272
- new (): IAdminForthDataSourceConnectorBase;
273
- }
274
- export interface IAdminForthAuth {
275
- verify(jwt: string, mustHaveType: string, decodeUser?: boolean): Promise<any>;
276
- issueJWT(payload: Object, type: string, expiresIn?: string): string;
277
- removeCustomCookie({ response, name }: {
278
- response: any;
279
- name: string;
280
- }): void;
281
- setCustomCookie({ response, payload }: {
282
- response: any;
283
- payload: {
284
- name: string;
285
- value: string;
286
- expiry: number;
287
- expirySeconds: number;
288
- httpOnly: boolean;
289
- };
290
- }): void;
291
- getCustomCookie({ cookies, name }: {
292
- cookies: {
293
- key: string;
294
- value: string;
295
- }[];
296
- name: string;
297
- }): string | null;
298
- setAuthCookie({ expireInDays, response, username, pk, }: {
299
- expireInDays?: number;
300
- response: any;
301
- username: string;
302
- pk: string;
303
- }): void;
304
- removeAuthCookie(response: any): void;
305
- getClientIp(headers: any): string;
306
- }
307
- export interface IAdminForthRestAPI {
308
- /**
309
- * Called by AdminForth to initialize all endpoints for REST API.
310
- */
311
- registerEndpoints(server: IHttpServer): void;
312
- /**
313
- * Called by login endpoint to process login callbacks. Also might be called by plugins, to prevent action if user is not allowed to login.
314
- * For example signup or login via google might want to check if user is allowed to login by calling this method.
315
- * @param adminUser - plugin/af pases current adminUser
316
- * @param toReturn - this is an object which will get status of login process. If at least one callback returns error or redirectTo, login process will be stopped (future callbacks will not be called).
317
- * @param response - http response object
318
- */
319
- processLoginCallbacks(adminUser: AdminUser, toReturn: {
320
- redirectTo?: string;
321
- allowedLogin: boolean;
322
- error?: string;
323
- }, response: any, extra: HttpExtra): Promise<void>;
324
- }
325
- export interface IAdminForth {
326
- config: AdminForthConfig;
327
- codeInjector: ICodeInjector;
328
- express: IHttpServer;
329
- restApi: IAdminForthRestAPI;
330
- activatedPlugins: Array<IAdminForthPlugin>;
331
- websocket: IWebSocketBroker;
332
- statuses: {
333
- dbDiscover: 'running' | 'done';
334
- };
335
- connectors: {
336
- [key: string]: IAdminForthDataSourceConnectorBase;
337
- };
338
- formatAdminForth(): string;
339
- tr(msg: string, category: string, lang: string, params: any, pluralizationNumber?: number): Promise<string>;
340
- createResourceRecord(params: {
341
- resource: AdminForthResource;
342
- record: any;
343
- adminUser: AdminUser;
344
- extra?: HttpExtra;
345
- }): Promise<{
346
- error?: string;
347
- createdRecord?: any;
348
- newRecordId?: any;
349
- }>;
350
- updateResourceRecord(params: {
351
- resource: AdminForthResource;
352
- recordId: any;
353
- record: any;
354
- oldRecord: any;
355
- adminUser: AdminUser;
356
- extra?: HttpExtra;
357
- updates?: never;
358
- } | {
359
- resource: AdminForthResource;
360
- recordId: any;
361
- record?: never;
362
- oldRecord: any;
363
- adminUser: AdminUser;
364
- extra?: HttpExtra;
365
- updates: any;
366
- }): Promise<{
367
- error?: string;
368
- }>;
369
- deleteResourceRecord(params: {
370
- resource: AdminForthResource;
371
- recordId: string;
372
- adminUser: AdminUser;
373
- record: any;
374
- extra?: HttpExtra;
375
- }): Promise<{
376
- error?: string;
377
- }>;
378
- auth: IAdminForthAuth;
379
- /**
380
- * Internal flag which indicates if AdminForth is running in hot reload mode.
381
- */
382
- runningHotReload: boolean;
383
- /**
384
- * Connects to databases defined in datasources and fetches described resource columns to find out data types and constraints.
385
- * You must call this method as soon as possible after AdminForth class is instantiated.
386
- */
387
- discoverDatabases(): Promise<void>;
388
- /**
389
- * Bundles AdminForth SPA by injecting custom components into internal pre-made SPA source code. It generates internally dist which then will be
390
- * served by AdminForth HTTP adapter.
391
- * Bundle is generated in /tmp folder so if you have ramfs or tmpfs this operation will be faster.
392
- *
393
- * We recommend calling this method from dedicated script which will be run by CI/CD pipeline in build time. This ensures lowest downtime for your users.
394
- * However for simple setup you can call it from your main script, and users will see some "AdminForth is bundling" message in the admin panel while app is bundling.
395
- */
396
- bundleNow({ hotReload, verbose }: {
397
- hotReload: boolean;
398
- verbose: boolean;
399
- }): Promise<void>;
400
- /**
401
- * Resource to get access to operational resources for data api fetching and manipulation.
402
- */
403
- resource(resourceId: string): IOperationalResource;
404
- /**
405
- * This method will be automatically called from AdminForth HTTP adapter to serve AdminForth SPA.
406
- */
407
- setupEndpoints(server: IHttpServer): void;
408
- /**
409
- * This method can be used when you want to get some plugin instances by class name.
410
- * Should be used for plugins which might have multiple instances with the same class name.
411
- * @param className - name of class which is used to identify plugin instance
412
- */
413
- getPluginsByClassName<T>(className: string): T[];
414
- /**
415
- * This method can be used when you want to get some plugin instance by class name.
416
- * Should be called only if you are sure there is only one plugin instance with this class name.
417
- * If several instances are found, this method will drop error.
418
- * @param className - name of class which is used to identify plugin instance
419
- *
420
- * Example:
421
- *
422
- * ```ts
423
- * const i18nPlugin = adminforth.getPluginByClassName\<I18nPlugin\>('I18nPlugin');
424
- * ```
425
- *
426
- */
427
- getPluginByClassName<T>(className: string): T;
428
- }
429
- export interface IAdminForthPlugin {
430
- adminforth: IAdminForth;
431
- pluginDir: string;
432
- customFolderName: string;
433
- pluginInstanceId: string;
434
- customFolderPath: string;
435
- pluginOptions: any;
436
- resourceConfig: AdminForthResource;
437
- className: string;
438
- /**
439
- * Before activating all plugins are sorted by this number and then activated in order.
440
- * If you want to make sure that your plugin is activated after some other plugin, set this number to higher value. (default is 0)
441
- */
442
- activationOrder: number;
443
- /**
444
- * AdminForth plugins concept is based on modification of full AdminForth configuration
445
- * to add some custom functionality. For example plugin might simply add custom field to resource by reusing
446
- * {@link AdminForthResourceColumn.components} object, then add some hook which will modify record before getting or saving it to database.
447
- *
448
- * So this method is core of AdminForth plugins. It allows to modify full resource configuration.
449
- * @param adminforth Instance of IAdminForth
450
- * @param resourceConfig Resource configuration object which will be modified by plugin
451
- */
452
- modifyResourceConfig(adminforth: IAdminForth, resourceConfig: AdminForthResource): void;
453
- componentPath(componentFile: string): string;
454
- /**
455
- * If plugin should support multiple installations per one resource, this function that should return unique string for each instance of plugin.
456
- * For example if plugin is installed for one column and this column defined as
457
- * `targetColumn` in plugin options, then this method should return `${pluginOptions.targetColumn}`.
458
- *
459
- * If plugin should support only one installation per resource, option can return 'single'
460
- * @param pluginOptions - options of plugin
461
- */
462
- instanceUniqueRepresentation(pluginOptions: any): string;
463
- /**
464
- * Optional method which will be called after AdminForth discovers all resources and their columns.
465
- * Can be used to validate types of columns, check if some columns are missing, etc.
466
- */
467
- validateConfigAfterDiscover?(adminforth: IAdminForth, resourceConfig: AdminForthResource): void;
468
- /**
469
- * Here you can register custom endpoints for your plugin.
470
- *
471
- * @param server
472
- */
473
- setupEndpoints(server: IHttpServer): void;
474
- }
475
- /**
476
- * Modify query to change how data is fetched from database.
477
- * Return ok: false and error: string to stop execution and show error message to user. Return ok: true to continue execution.
478
- */
479
- export type BeforeDataSourceRequestFunction = (params: {
480
- resource: AdminForthResource;
481
- adminUser: AdminUser;
482
- query: any;
483
- extra: {
484
- body: any;
485
- query: Record<string, string>;
486
- headers: Record<string, string>;
487
- cookies: Record<string, string>;
488
- requestUrl: string;
489
- };
490
- adminforth: IAdminForth;
491
- }) => Promise<{
492
- ok: boolean;
493
- error?: string;
494
- newRecordId?: string;
495
- }>;
496
- /**
497
- * Modify response to change how data is returned after fetching from database.
498
- * Return ok: false and error: string to stop execution and show error message to user. Return ok: true to continue execution.
499
- */
500
- export type AfterDataSourceResponseFunction = (params: {
501
- resource: AdminForthResource;
502
- adminUser: AdminUser;
503
- query: any;
504
- response: any;
505
- extra: {
506
- body: any;
507
- query: Record<string, string>;
508
- headers: Record<string, string>;
509
- cookies: {
510
- key: string;
511
- value: string;
512
- }[];
513
- requestUrl: string;
514
- };
515
- adminforth: IAdminForth;
516
- }) => Promise<{
517
- ok: boolean;
518
- error?: string;
519
- }>;
520
- export interface HttpExtra {
521
- body: any;
522
- query: Record<string, string>;
523
- headers: Record<string, string>;
524
- cookies: Record<string, string>;
525
- requestUrl: string;
526
- }
527
- /**
528
- * Modify record to change how data is saved to database.
529
- * Return ok: false and error: string to stop execution and show error message to user. Return ok: true to continue execution.
530
- */
531
- export type BeforeDeleteSaveFunction = (params: {
532
- resource: AdminForthResource;
533
- recordId: any;
534
- adminUser: AdminUser;
535
- record: any;
536
- adminforth: IAdminForth;
537
- extra?: HttpExtra;
538
- }) => Promise<{
539
- ok: boolean;
540
- error?: string;
541
- }>;
542
- export type BeforeEditSaveFunction = (params: {
543
- resource: AdminForthResource;
544
- recordId: any;
545
- adminUser: AdminUser;
546
- updates: any;
547
- record: any;
548
- oldRecord: any;
549
- adminforth: IAdminForth;
550
- extra?: HttpExtra;
551
- }) => Promise<{
552
- ok: boolean;
553
- error?: string | null;
554
- }>;
555
- export type BeforeCreateSaveFunction = (params: {
556
- resource: AdminForthResource;
557
- adminUser: AdminUser;
558
- record: any;
559
- adminforth: IAdminForth;
560
- extra?: HttpExtra;
561
- }) => Promise<{
562
- ok: boolean;
563
- error?: string | null;
564
- newRecordId?: string;
565
- }>;
566
- export type AfterCreateSaveFunction = (params: {
567
- resource: AdminForthResource;
568
- recordId: any;
569
- adminUser: AdminUser;
570
- record: any;
571
- adminforth: IAdminForth;
572
- recordWithVirtualColumns?: any;
573
- extra?: HttpExtra;
574
- }) => Promise<{
575
- ok: boolean;
576
- error?: string;
577
- }>;
578
- /**
579
- * Modify record to change how data is saved to database.
580
- * Return ok: false and error: string to stop execution and show error message to user. Return ok: true to continue execution.
581
- */
582
- export type AfterDeleteSaveFunction = (params: {
583
- resource: AdminForthResource;
584
- recordId: any;
585
- adminUser: AdminUser;
586
- record: any;
587
- adminforth: IAdminForth;
588
- extra?: HttpExtra;
589
- }) => Promise<{
590
- ok: boolean;
591
- error?: string;
592
- }>;
593
- export type AfterEditSaveFunction = (params: {
594
- resource: AdminForthResource;
595
- recordId: any;
596
- adminUser: AdminUser;
597
- updates: any;
598
- record: any;
599
- oldRecord: any;
600
- adminforth: IAdminForth;
601
- extra?: HttpExtra;
602
- }) => Promise<{
603
- ok: boolean;
604
- error?: string;
605
- }>;
606
- /**
607
- * Allow to get user data before login confirmation, will triger when user try to login.
608
- */
609
- export type BeforeLoginConfirmationFunction = (params?: {
610
- adminUser: AdminUser;
611
- response: IAdminForthHttpResponse;
612
- adminforth: IAdminForth;
613
- extra?: HttpExtra;
614
- rememberMeDays?: number;
615
- }) => Promise<{
616
- error?: string;
617
- body: {
618
- redirectTo?: string;
619
- allowedLogin?: boolean;
620
- };
621
- }>;
622
- /**
623
- * Allow to make extra authorization
624
- */
625
- export type AdminUserAuthorizeFunction = ((params?: {
626
- adminUser: AdminUser;
627
- response: IAdminForthHttpResponse;
628
- adminforth: IAdminForth;
629
- extra?: HttpExtra;
630
- }) => Promise<{
631
- error?: string;
632
- allowed?: boolean;
633
- }>);
634
- /**
635
- * Data source describes database connection which will be used to fetch data for resources.
636
- * Each resource should use one data source.
637
- */
638
- export type AdminForthDataSource = {
639
- /**
640
- * ID of datasource which you will use in resources to specify from which database to fetch data from
641
- */
642
- id: string;
643
- /**
644
- * URL to database. Examples:
645
- *
646
- * - MongoDB: `mongodb://<user>:<password>@<host>:<port>/<database>`
647
- * - PostgreSQL: `postgresql://<user>:<password>@<host>:<port>/<database>`
648
- * - SQLite: `sqlite://<path>`
649
- */
650
- url: string;
651
- };
652
- type AdminForthPageDeclaration = {
653
- path: string;
654
- component: AdminForthComponentDeclaration;
655
- };
656
- interface AdminForthInputConfigCustomization {
657
- /**
658
- * Your app name
659
- */
660
- brandName?: string;
661
- /**
662
- * Whether to use single theme for the app
663
- */
664
- singleTheme?: 'light' | 'dark';
665
- /**
666
- * Whether to show brand name in sidebar
667
- * default is true
668
- */
669
- showBrandNameInSidebar?: boolean;
670
- /**
671
- * Whether to show brand logo in sidebar
672
- * default is true
673
- */
674
- showBrandLogoInSidebar?: boolean;
675
- /**
676
- * Path to your app logo
677
- *
678
- * Example:
679
- * Place file `logo.svg` to `./custom` folder and set this option:
680
- *
681
- * ```ts
682
- * brandLogo: '@@/logo.svg',
683
- * ```
684
- *
685
- */
686
- brandLogo?: string;
687
- /**
688
- * Path to your app logo for icon only sidebar
689
- *
690
- * Example:
691
- * Place file `logo.svg` to `./custom` folder and set this option:
692
- *
693
- */
694
- iconOnlySidebar?: {
695
- logo?: string;
696
- enabled?: boolean;
697
- /**
698
- * Width of expanded sidebar (default: '16.5rem')
699
- */
700
- expandedSidebarWidth?: string;
701
- };
702
- /**
703
- * Path to your app favicon
704
- *
705
- * Example:
706
- * Place file `favicon.png` to `./custom` folder and set this option:
707
- *
708
- * ```ts
709
- * favicon: '@@/favicon.png',
710
- * ```
711
- */
712
- favicon?: string;
713
- /**
714
- * DayJS format string for all dates in the app.
715
- * Defaulted to 'MMM D, YYYY'
716
- */
717
- datesFormat?: string;
718
- /**
719
- * DayJS format string for all datetimes in the app.
720
- * Defaulted to 'HH:mm:ss'
721
- */
722
- timeFormat?: string;
723
- /**
724
- * HTML title tag value, defaults to brandName
725
- */
726
- title?: string;
727
- /**
728
- * Placeholder for empty fields in lists and show views, by default empty string ''
729
- */
730
- emptyFieldPlaceholder?: {
731
- show?: string;
732
- list?: string;
733
- } | string;
734
- /**
735
- * Relative or absolute path to custom components directory
736
- * By default equals `./custom`.
737
- *
738
- * Custom .vue files, images, and any other assets placed in this directory can be accessed in AdminForth components and configs with `@@/`.
739
- *
740
- * For example if file path is `./custom/comp/my.vue`, you can use it in AdminForth config like this:
741
- *
742
- * ```ts
743
- * components: {
744
- * show: '@@/comp/my.vue',
745
- * }
746
- * ```
747
- *
748
- */
749
- customComponentsDir?: string;
750
- /**
751
- * Path to custom .ts file which allows to inject custom Vue uses in SPA or add custom imports.
752
- *
753
- * Example: Create file: `./custom/vue-uses.ts` with next content:
754
- *
755
- * ```ts
756
- * import HighchartsVue from 'highcharts-vue';
757
- * // import '@@/custom.scss'; // here is how you can import custom styles
758
- *
759
- * export default function (app) {
760
- * app.use(HighchartsVue);
761
- * }
762
- * ```
763
- *
764
- * Install HighCharts into custom folder:
765
- *
766
- * ```bashcreating rec
767
- * cd custom
768
- * npm init -y
769
- * npm install highcharts highcharts-vue
770
- * ```
771
- *
772
- * And specify vueUsesFile in AdminForth config:
773
- *
774
- * ```ts
775
- * vueUsesFile: '@@/vue-uses.ts',
776
- * ```
777
- *
778
- */
779
- vueUsesFile?: string;
780
- /**
781
- * Object to redefine default styles for AdminForth components. Use this file as reference for all possible adjustments https://github.com/devforth/adminforth/blob/main/adminforth/modules/styles.ts
782
- */
783
- styles?: Object;
784
- /**
785
- * Description of custom pages which will let register custom pages for custom routes in AdminForth.
786
- */
787
- customPages?: Array<AdminForthPageDeclaration>;
788
- /**
789
- * Function to return custom badge in side bar for users. Can return text or html
790
- * If function is not passed or returns null, badge will not be shown.
791
- * Execution is done on admin app load.
792
- */
793
- announcementBadge?: (user: AdminUser) => AnnouncementBadgeResponse;
794
- /**
795
- * Custom panel components or array of components which will be displayed in the login form
796
- * right after the inputs. Use it to add custom authorization methods like social login or other custom fields e.g. 'reset'
797
- * password link.
798
- */
799
- loginPageInjections?: {
800
- underInputs?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>;
801
- underLoginButton?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>;
802
- panelHeader?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>;
803
- };
804
- /**
805
- * Custom panel components or array of components which will be displayed in different parts of the admin panel.
806
- */
807
- globalInjections?: {
808
- userMenu?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>;
809
- header?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>;
810
- sidebar?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>;
811
- sidebarTop?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>;
812
- everyPageBottom?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>;
813
- };
814
- /**
815
- * Allows adding custom elements (e.g., &lt;link&gt;, &lt;script&gt;, &lt;meta&gt;) to the &lt;head&gt; of the HTML document.
816
- * Each item must include a tag name and a set of attributes.
817
- */
818
- customHeadItems?: {
819
- tagName: string;
820
- attributes: Record<string, string | boolean>;
821
- innerCode?: string;
822
- }[];
823
- }
824
- export interface AdminForthActionInput {
825
- name: string;
826
- showIn?: {
827
- list?: boolean;
828
- showButton?: boolean;
829
- showThreeDotsMenu?: boolean;
830
- };
831
- allowed?: (params: {
832
- adminUser: AdminUser;
833
- standardAllowedActions: AllowedActions;
834
- }) => boolean;
835
- url?: string;
836
- action?: (params: {
837
- adminforth: IAdminForth;
838
- resource: AdminForthResource;
839
- recordId: string;
840
- adminUser: AdminUser;
841
- extra?: HttpExtra;
842
- tr: Function;
843
- }) => Promise<{
844
- ok: boolean;
845
- error?: string;
846
- message?: string;
847
- }>;
848
- icon?: string;
849
- id?: string;
850
- customComponent?: AdminForthComponentDeclaration;
851
- }
852
- export interface AdminForthResourceInput extends Omit<NonNullable<AdminForthResourceInputCommon>, 'columns' | 'hooks' | 'options'> {
853
- /**
854
- * Array of plugins which will be used to modify resource configuration.
855
- *
856
- */
857
- plugins?: Array<IAdminForthPlugin>;
858
- /**
859
- * Hooks allow you to change the data on different stages of resource lifecycle.
860
- * Hooks are functions which will be called on backend side (only backend side).
861
- */
862
- hooks?: {
863
- show?: {
864
- /**
865
- * Typical use-cases:
866
- * - request additional data from database before returning to frontend for soft-join
867
- */
868
- beforeDatasourceRequest?: BeforeDataSourceRequestFunction | Array<BeforeDataSourceRequestFunction>;
869
- /**
870
- * Typical use-cases:
871
- * - Transform value for some field for record returned from database before returning to frontend (minimize, sanitize, etc)
872
- * - If some-why you can't use `backendOnly` you can cleanup sensitive fields here
873
- * - Attach additional data to record before returning to frontend
874
- */
875
- afterDatasourceResponse?: AfterDataSourceResponseFunction | Array<AfterDataSourceResponseFunction>;
876
- };
877
- list?: {
878
- /**
879
- * Typical use-cases:
880
- * - add additional filters in addition to what user selected before fetching data from database.
881
- * - same as hooks.show.beforeDatasourceRequest
882
- */
883
- beforeDatasourceRequest?: BeforeDataSourceRequestFunction | Array<BeforeDataSourceRequestFunction>;
884
- /**
885
- * Typical use-cases:
886
- * - Same as hooks.show.afterDatasourceResponse but applied for all records returned from database for
887
- * showing in list view, e.g. add new field to each record in list view
888
- */
889
- afterDatasourceResponse?: AfterDataSourceResponseFunction | Array<AfterDataSourceResponseFunction>;
890
- };
891
- create?: {
892
- /**
893
- * Typical use-cases:
894
- * - Validate record before saving to database and interrupt execution if validation failed (`allowedActions.create` should be preferred in most cases)
895
- * - fill-in adminUser as creator of record
896
- * - Attach additional data to record before saving to database (mostly fillOnCreate should be used instead)
897
- */
898
- beforeSave?: BeforeCreateSaveFunction | Array<BeforeCreateSaveFunction>;
899
- /**
900
- * Typical use-cases:
901
- * - Initiate some trigger after record saved to database (e.g sync to another datasource)
902
- */
903
- afterSave?: AfterCreateSaveFunction | Array<AfterCreateSaveFunction>;
904
- };
905
- edit?: {
906
- /**
907
- * Typical use-cases:
908
- * - Same as hooks.create.beforeSave but for edit page
909
- */
910
- beforeSave?: BeforeEditSaveFunction | Array<BeforeEditSaveFunction>;
911
- /**
912
- * Typical use-cases:
913
- * - Same as hooks.create.afterSave but for edit page
914
- */
915
- afterSave?: AfterEditSaveFunction | Array<AfterEditSaveFunction>;
916
- };
917
- delete?: {
918
- /**
919
- * Typical use-cases:
920
- * - Validate that record can be deleted and interrupt execution if validation failed (`allowedActions.delete` should be preferred in most cases)
921
- */
922
- beforeSave?: BeforeDeleteSaveFunction | Array<BeforeDeleteSaveFunction>;
923
- /**
924
- * Typical use-cases:
925
- * - Initiate some trigger after record deleted from database (e.g sync to another datasource)
926
- */
927
- afterSave?: BeforeDeleteSaveFunction | Array<BeforeDeleteSaveFunction>;
928
- };
929
- };
930
- options?: ResourceOptionsInput;
931
- columns: Array<AdminForthResourceColumnInput>;
932
- dataSourceColumns?: Array<AdminForthResourceColumn>;
933
- }
934
- /**
935
- * Main configuration object for AdminForth
936
- */
937
- export interface AdminForthInputConfig {
938
- /**
939
- * Authorization module configuration
940
- */
941
- auth?: {
942
- /**
943
- * Resource ID for resource which stores user table.
944
- * Resource is a table in database where users will be stored and fetched from. Resources and their ids are defined in resources section of the config.
945
- * In other words this setting is a reference to a table in database where users will be fetched from on login.
946
- */
947
- usersResourceId?: string;
948
- /**
949
- * Legacy field left for backward compatibility. Use usersResourceId instead.
950
- */
951
- resourceId?: string;
952
- /**
953
- * Field name (column name) in user resource which will be used as username for searching user in database during login.
954
- * Can be e.g. 'email' or 'username'
955
- */
956
- usernameField: string;
957
- /**
958
- * Field name (column name) in user resource which will be used to get hash of password.
959
- * Can be e.g. 'passwordHash'
960
- */
961
- passwordHashField: string;
962
- /**
963
- * File path to custom background image for login page
964
- * Example:
965
- * Place file `login-background.jpg` to `./custom` folder and set this option:
966
- *
967
- * ```ts
968
- * loginBackgroundImage: '@@/login-background.jpg',
969
- * ```
970
- */
971
- loginBackgroundImage?: string;
972
- /**
973
- * Position of background image on login page
974
- * 'over' - image will be displayed over full login page under login form
975
- * '1/2' - image will be displayed on left 1/2 of login page
976
- *
977
- * Default: '1/2'
978
- */
979
- loginBackgroundPosition?: 'over' | '1/2' | '1/3' | '2/3' | '3/4' | '2/5' | '3/5';
980
- /**
981
- * If true, background blend mode will be removed from login background image when position is 'over'
982
- *
983
- * Default: false
984
- */
985
- removeBackgroundBlendMode?: boolean;
986
- /**
987
- * Function or functions which will be called before user try to login.
988
- * Each function will resive User object as an argument
989
- */
990
- beforeLoginConfirmation?: BeforeLoginConfirmationFunction | Array<BeforeLoginConfirmationFunction>;
991
- /**
992
- * Array of functions which will be called before any request to AdminForth API.
993
- */
994
- adminUserAuthorize?: AdminUserAuthorizeFunction | Array<AdminUserAuthorizeFunction>;
995
- /**
996
- * Optionally if your users table has a field(column) with full name, you can set it here.
997
- * This field will be used to display user name in the top right corner of the admin panel.
998
- */
999
- userFullNameField?: string;
1000
- /**
1001
- * Pair of login and pass substitution for demo mode. Split by ':'
1002
- * ! This option is for demo purposes only, never use it for your projects
1003
- */
1004
- demoCredentials?: string;
1005
- /**
1006
- * Any prompt to show users on login. Supports HTML.
1007
- */
1008
- loginPromptHTML?: string | (() => string | void | undefined | Promise<string | void | undefined>) | undefined;
1009
- /**
1010
- * Remember me days for "Remember Me" checkbox on login page.
1011
- * If not set or set to null/0/undefined, "Remember Me" checkbox will not be displayed.
1012
- * If rememberMeDays is set, then users who check "Remember Me" will be staying logged in for this amount of days.
1013
- */
1014
- rememberMeDays?: number;
1015
- /**
1016
- * Can be used to limit user access when subscribing from frontend to websocket topics.
1017
- * @param topic - topic where user is trying to subscribe
1018
- * @param user - user object
1019
- * @returns - boolean, true if user is allowed to subscribe to this topic, false otherwise
1020
- */
1021
- websocketTopicAuth?: (topic: string, user: AdminUser) => Promise<boolean>;
1022
- /**
1023
- * callback which will be called after user subscribes to websocket topic
1024
- * @param topic - topic on which user subscribed
1025
- * @param user - user object
1026
- * @returns
1027
- */
1028
- websocketSubscribed?: (topic: string, user: AdminUser) => void;
1029
- /**
1030
- * Client IP header name. If set, AdminForth will use this header to get client IP address.
1031
- * Otherwise it will use first IP address from X-Forwarded-For header.
1032
- * If you are using Cloudflare, set this to 'CF-Connecting-IP'. Case-insensitive.
1033
- */
1034
- clientIpHeader?: string;
1035
- /**
1036
- * Add custom page to the settings page
1037
- */
1038
- userMenuSettingsPages: {
1039
- icon?: string;
1040
- pageLabel: string;
1041
- slug?: string;
1042
- component: string;
1043
- isVisible?: (adminUser: AdminUser) => boolean;
1044
- }[];
1045
- };
1046
- /**
1047
- * Array of resources which will be displayed in the admin panel.
1048
- * Resource represents one table or collection in database.
1049
- * Each resource has its own configuration.
1050
- */
1051
- resources: Array<AdminForthResourceInput>;
1052
- /**
1053
- * Array of left sidebar menu items which will be displayed in the admin panel.
1054
- * Menu items can be links to resources or custom pages.
1055
- * Menu items can be grouped.
1056
- *
1057
- */
1058
- menu: Array<AdminForthConfigMenuItem>;
1059
- /**
1060
- * If you want use custom DataSource which is not supported by AdminForth yet, you can define it's class here
1061
- *
1062
- */
1063
- databaseConnectors?: {
1064
- [key: string]: IAdminForthDataSourceConnectorConstructor;
1065
- };
1066
- /**
1067
- * List of data sources which will be used to fetch data for resources.
1068
- * Datasource is one database connection
1069
- *
1070
- */
1071
- dataSources: Array<AdminForthDataSource>;
1072
- /**
1073
- * Settings which allow you to customize AdminForth
1074
- *
1075
- */
1076
- customization?: AdminForthInputConfigCustomization;
1077
- /**
1078
- * If you want to Serve AdminForth from a subdirectory, e.g. on example.com/backoffice, you can specify it like:
1079
- *
1080
- * ```ts
1081
- * baseUrl: '/backoffice',
1082
- * ```
1083
- *
1084
- */
1085
- baseUrl?: string;
1086
- }
1087
- export interface AdminForthConfigCustomization extends Omit<AdminForthInputConfigCustomization, 'loginPageInjections' | 'globalInjections'> {
1088
- brandName: string;
1089
- dateFormats: string;
1090
- timeFormat: string;
1091
- /**
1092
- * Slug which will be used on tech side e.g. to store cookies separately.
1093
- * Created automatically from brandName if not set.
1094
- */
1095
- brandNameSlug: string;
1096
- showBrandNameInSidebar: boolean;
1097
- customPages: Array<AdminForthPageDeclaration>;
1098
- loginPageInjections: {
1099
- underInputs: Array<AdminForthComponentDeclarationFull>;
1100
- underLoginButton?: AdminForthComponentDeclaration | Array<AdminForthComponentDeclaration>;
1101
- panelHeader: Array<AdminForthComponentDeclarationFull>;
1102
- };
1103
- globalInjections: {
1104
- userMenu: Array<AdminForthComponentDeclarationFull>;
1105
- header: Array<AdminForthComponentDeclarationFull>;
1106
- sidebar: Array<AdminForthComponentDeclarationFull>;
1107
- sidebarTop: Array<AdminForthComponentDeclarationFull>;
1108
- everyPageBottom: Array<AdminForthComponentDeclarationFull>;
1109
- };
1110
- customHeadItems?: {
1111
- tagName: string;
1112
- attributes: Record<string, string | boolean>;
1113
- innerCode?: string;
1114
- }[];
1115
- }
1116
- export interface AdminForthConfig extends Omit<AdminForthInputConfig, 'customization' | 'resources'> {
1117
- baseUrl: string;
1118
- baseUrlSlashed: string;
1119
- customization: AdminForthConfigCustomization;
1120
- resources: Array<AdminForthResource>;
1121
- }
1122
- export type FDataFilter = (field: string, value: any) => IAdminForthSingleFilter;
1123
- export declare class Filters {
1124
- static EQ(field: string, value: any): IAdminForthSingleFilter;
1125
- static NEQ(field: string, value: any): IAdminForthSingleFilter;
1126
- static GT(field: string, value: any): IAdminForthSingleFilter;
1127
- static GTE(field: string, value: any): IAdminForthSingleFilter;
1128
- static LT(field: string, value: any): IAdminForthSingleFilter;
1129
- static LTE(field: string, value: any): IAdminForthSingleFilter;
1130
- static IN(field: string, value: any): IAdminForthSingleFilter;
1131
- static NOT_IN(field: string, value: any): IAdminForthSingleFilter;
1132
- static LIKE(field: string, value: any): IAdminForthSingleFilter;
1133
- static ILIKE(field: string, value: any): IAdminForthSingleFilter;
1134
- static GT_FIELD(leftField: string, rightField: string): IAdminForthSingleFilter;
1135
- static GTE_FIELD(leftField: string, rightField: string): IAdminForthSingleFilter;
1136
- static LT_FIELD(leftField: string, rightField: string): IAdminForthSingleFilter;
1137
- static LTE_FIELD(leftField: string, rightField: string): IAdminForthSingleFilter;
1138
- static AND(...args: (IAdminForthSingleFilter | IAdminForthAndOrFilter | Array<IAdminForthSingleFilter | IAdminForthAndOrFilter>)[]): IAdminForthAndOrFilter;
1139
- static OR(...args: (IAdminForthSingleFilter | IAdminForthAndOrFilter | Array<IAdminForthSingleFilter | IAdminForthAndOrFilter>)[]): IAdminForthAndOrFilter;
1140
- }
1141
- export type FDataSort = (field: string, direction: AdminForthSortDirections) => IAdminForthSort;
1142
- export declare class Sorts {
1143
- static ASC(field: string): IAdminForthSort;
1144
- static DESC(field: string): IAdminForthSort;
1145
- }
1146
- export interface IOperationalResource {
1147
- get: (filter: IAdminForthSingleFilter | IAdminForthAndOrFilter | Array<IAdminForthSingleFilter | IAdminForthAndOrFilter>) => Promise<any | null>;
1148
- list: (filter: IAdminForthSingleFilter | IAdminForthAndOrFilter | Array<IAdminForthSingleFilter | IAdminForthAndOrFilter>, limit?: number, offset?: number, sort?: IAdminForthSort | IAdminForthSort[]) => Promise<any[]>;
1149
- count: (filter?: IAdminForthSingleFilter | IAdminForthAndOrFilter | Array<IAdminForthSingleFilter | IAdminForthAndOrFilter>) => Promise<number>;
1150
- create: (record: any) => Promise<{
1151
- ok: boolean;
1152
- createdRecord: any;
1153
- error?: string;
1154
- }>;
1155
- update: (primaryKey: any, record: any) => Promise<any>;
1156
- delete: (primaryKey: any) => Promise<boolean>;
1157
- dataConnector: IAdminForthDataSourceConnectorBase;
1158
- }
1159
- /**
1160
- * Defines whether user has access to an action, can statically be Boolean
1161
- * or function which returns Boolean or string with error message
1162
- *
1163
- */
1164
- export type AllowedActionValue = boolean | (({ adminUser, resource, meta, source, adminforth }: {
1165
- adminUser: AdminUser;
1166
- resource: AdminForthResource;
1167
- /**
1168
- * Meta object which will pass request information just in case
1169
- */
1170
- meta: any;
1171
- /**
1172
- * Source of the check
1173
- */
1174
- source: ActionCheckSource;
1175
- /**
1176
- * Instance of AdminForth, can be used e.g. to call data API adminforth.resource(resourceId)...
1177
- */
1178
- adminforth: IAdminForth;
1179
- }) => Promise<boolean | string>);
1180
- /**
1181
- * Object which describes allowed actions for user.
1182
- */
1183
- export type AllowedActionsInput = {
1184
- [key in AllowedActionsEnum]?: AllowedActionValue;
1185
- } & {
1186
- all?: AllowedActionValue;
1187
- };
1188
- export type AllowedActions = {
1189
- [key in AllowedActionsEnum]: AllowedActionValue;
1190
- };
1191
- /**
1192
- * General options for resource.
1193
- */
1194
- export interface ResourceOptionsInput extends Omit<NonNullable<AdminForthResourceInputCommon['options']>, 'allowedActions' | 'bulkActions'> {
1195
- /**
1196
- * Custom bulk actions list. Bulk actions available in list view when user selects multiple records by
1197
- * using checkboxes.
1198
- */
1199
- bulkActions?: Array<AdminForthBulkAction>;
1200
- /**
1201
- * Allowed actions for resource.
1202
- *
1203
- * Example:
1204
- *
1205
- * ```ts
1206
- * allowedActions: {
1207
- * create: ({ resource, adminUser }) => {
1208
- * // Allow only superadmin to create records
1209
- * return adminUser.dbUser.role === 'superadmin';
1210
- * },
1211
- * delete: false, // disable delete action for all users
1212
- * }
1213
- * ```
1214
- *
1215
- */
1216
- allowedActions?: AllowedActionsInput;
1217
- /**
1218
- * Array of actions which will be displayed in the resource.
1219
- *
1220
- * Example:
1221
- *
1222
- * ```ts
1223
- * actions: [
1224
- * {
1225
- * name: 'Auto submit',
1226
- * allowed: ({ adminUser, standardAllowedActions }) => {
1227
- * return adminUser.dbUser.role === 'superadmin';
1228
- * },
1229
- * action: ({ adminUser, resource, recordId, adminforth, extra, tr }) => {
1230
- * console.log("auto submit", recordId, adminUser);
1231
- * return { ok: true, successMessage: "Auto submitted" };
1232
- * },
1233
- * showIn: {
1234
- * list: true,
1235
- * showButton: true,
1236
- * showThreeDotsMenu: true,
1237
- * },
1238
- * },
1239
- * ]
1240
- * ```
1241
- */
1242
- actions?: Array<AdminForthActionInput>;
1243
- }
1244
- export interface ResourceOptions extends Omit<ResourceOptionsInput, 'allowedActions'> {
1245
- allowedActions: AllowedActions;
1246
- actions?: Array<AdminForthActionInput>;
1247
- }
1248
- /**
1249
- * Resource describes one table or collection in database.
1250
- * AdminForth generates set of pages for 'list', 'show', 'edit', 'create', 'filter' operations for each resource.
1251
- */
1252
- export interface AdminForthResource extends Omit<AdminForthResourceInput, 'options' | 'columns'> {
1253
- /**
1254
- * Array of plugins which will be used to modify resource configuration.
1255
- *
1256
- */
1257
- plugins?: Array<IAdminForthPlugin>;
1258
- /**
1259
- * Hooks allow you to change the data on different stages of resource lifecycle.
1260
- * Hooks are functions which will be called on backend side (only backend side).
1261
- */
1262
- hooks?: {
1263
- show?: {
1264
- /**
1265
- * Typical use-cases:
1266
- * - request additional data from database before returning to frontend for soft-join
1267
- */
1268
- beforeDatasourceRequest?: Array<BeforeDataSourceRequestFunction>;
1269
- /**
1270
- * Typical use-cases:
1271
- * - Transform value for some field for record returned from database before returning to frontend (minimize, sanitize, etc)
1272
- * - If some-why you can't use `backendOnly` you can cleanup sensitive fields here
1273
- * - Attach additional data to record before returning to frontend
1274
- */
1275
- afterDatasourceResponse?: Array<AfterDataSourceResponseFunction>;
1276
- };
1277
- list?: {
1278
- /**
1279
- * Typical use-cases:
1280
- * - add additional filters in addition to what user selected before fetching data from database.
1281
- * - same as hooks.show.beforeDatasourceRequest
1282
- */
1283
- beforeDatasourceRequest?: Array<BeforeDataSourceRequestFunction>;
1284
- /**
1285
- * Typical use-cases:
1286
- * - Same as hooks.show.afterDatasourceResponse but applied for all records returned from database for
1287
- * showing in list view, e.g. add new field to each record in list view
1288
- */
1289
- afterDatasourceResponse?: Array<AfterDataSourceResponseFunction>;
1290
- };
1291
- create?: {
1292
- /**
1293
- * Should return `ok: true` to continue saving pipeline and allow creating record in database, and `ok: false` to interrupt pipeline and prevent record creation.
1294
- * If you need to show error on UI, set `error: \<error message\>` in response.
1295
- *
1296
- * Typical use-cases:
1297
- * - Create record by custom code (return `{ ok: false, newRecordId: <id of created record from custom code> }`)
1298
- * - Validate record before saving to database and interrupt execution if validation failed (return `{ ok: false, error: <validation error> }`), though `allowedActions.create` should be preferred in most cases
1299
- * - fill-in adminUser as creator of record (set `record.<some field> = x; return \{ ok: true \}`)
1300
- * - Attach additional data to record before saving to database (mostly fillOnCreate should be used instead)
1301
- */
1302
- beforeSave?: Array<BeforeCreateSaveFunction>;
1303
- /**
1304
- * Typical use-cases:
1305
- * - Initiate some trigger after record saved to database (e.g sync to another datasource)
1306
- */
1307
- afterSave?: Array<AfterCreateSaveFunction>;
1308
- };
1309
- edit?: {
1310
- /**
1311
- * Typical use-cases:
1312
- * - Same as hooks.create.beforeSave but for edit page
1313
- */
1314
- beforeSave?: Array<BeforeEditSaveFunction>;
1315
- /**
1316
- * Typical use-cases:
1317
- * - Same as hooks.create.afterSave but for edit page
1318
- */
1319
- afterSave?: Array<AfterEditSaveFunction>;
1320
- };
1321
- delete?: {
1322
- /**
1323
- * Typical use-cases:
1324
- * - Validate that record can be deleted and interrupt execution if validation failed (`allowedActions.delete` should be preferred in most cases)
1325
- */
1326
- beforeSave?: Array<BeforeDeleteSaveFunction>;
1327
- /**
1328
- * Typical use-cases:
1329
- * - Initiate some trigger after record deleted from database (e.g sync to another datasource)
1330
- */
1331
- afterSave?: Array<BeforeDeleteSaveFunction>;
1332
- };
1333
- };
1334
- options: ResourceOptions;
1335
- columns: Array<AdminForthResourceColumn>;
1336
- dataSourceColumns: Array<AdminForthResourceColumn>;
1337
- recordLabel: (record: any) => string;
1338
- label: string;
1339
- resourceId: string;
1340
- }
1341
- export interface AdminForthBulkAction extends AdminForthBulkActionCommon {
1342
- /**
1343
- * Callback which will be called on backend when user clicks on action button.
1344
- * It should return Promise which will be resolved when action is done.
1345
- */
1346
- action: ({ resource, selectedIds, adminUser, tr }: {
1347
- resource: AdminForthResource;
1348
- selectedIds: Array<any>;
1349
- adminUser: AdminUser;
1350
- tr: (key: string, category?: string, params?: any) => string;
1351
- }) => Promise<{
1352
- ok: boolean;
1353
- error?: string;
1354
- successMessage?: string;
1355
- }>;
1356
- /**
1357
- * Allowed callback called to check whether action is allowed for user.
1358
- * 1. It called first time when user goes to list view. If callback returns false, action button will be hidden on list view.
1359
- * 2. This same callback called second time when user clicks an action button. If callback returns false, action will not be executed.
1360
- * In second time selectedIds will be passed to callback (because checkbox for items are selected), so you can use this to make additional
1361
- * checks ( for example to check if user has permission for certain records ).
1362
- *
1363
- * Example:
1364
- *
1365
- * ```ts
1366
- * allowed: async ({ resource, adminUser, selectedIds }) => {
1367
- * if (adminUser.dbUser.role !== 'superadmin') {
1368
- * return false;
1369
- * }
1370
- * return true;
1371
- * }
1372
- * ```
1373
- *
1374
- */
1375
- allowed?: ({ resource, adminUser, selectedIds, allowedActions }: {
1376
- /**
1377
- * recordIds will be passed only once user tries to perform bulk action by clicking on button
1378
- */
1379
- selectedIds?: Array<any>;
1380
- resource: AdminForthResource;
1381
- /**
1382
- * Admin user object
1383
- */
1384
- adminUser: AdminUser;
1385
- /**
1386
- * Allowed standard actions for current user resolved by calling allowedActions callbacks if they are passed.
1387
- * You can use this variable to rely on standard actions permissions. E.g. if you have custom actions "Mark as read", you
1388
- * might want to allow it only for users who have "edit" action allowed:
1389
- *
1390
- * Example:
1391
- *
1392
- * ```ts
1393
- *
1394
- * options: \{
1395
- * bulkActions: [
1396
- * \{
1397
- * label: 'Mark as read',
1398
- * action: async (\{ resource, recordIds \}) => \{
1399
- * await markAsRead(recordIds);
1400
- * \},
1401
- * allowed: (\{ allowedActions \}) => allowedActions.edit,
1402
- * \}
1403
- * ],
1404
- * allowedActions: \{
1405
- * edit: (\{ resource, adminUser, recordIds \}) => \{
1406
- * return adminUser.dbUser.role === 'superadmin';
1407
- * \}
1408
- * \}
1409
- * \}
1410
- * ```
1411
- *
1412
- */
1413
- allowedActions: AllowedActionsResolved;
1414
- }) => Promise<boolean>;
1415
- }
1416
- export interface AdminForthForeignResource extends AdminForthForeignResourceCommon {
1417
- hooks?: {
1418
- dropdownList?: {
1419
- beforeDatasourceRequest?: BeforeDataSourceRequestFunction | Array<BeforeDataSourceRequestFunction>;
1420
- afterDatasourceResponse?: AfterDataSourceResponseFunction | Array<AfterDataSourceResponseFunction>;
1421
- };
1422
- };
1423
- }
1424
- export type ShowInModernInput = {
1425
- [key in AdminForthResourcePages]?: AllowedActionValue;
1426
- } & {
1427
- all?: AllowedActionValue;
1428
- };
1429
- export type ShowInLegacyInput = Array<AdminForthResourcePages | keyof typeof AdminForthResourcePages>;
1430
- /**
1431
- * Object which describes on what pages should column be displayed on.
1432
- */
1433
- export type ShowInInput = ShowInModernInput | ShowInLegacyInput;
1434
- export type ShowIn = {
1435
- [key in AdminForthResourcePages]: AllowedActionValue;
1436
- };
1437
- export type BackendOnlyInput = boolean | ((p: {
1438
- adminUser: AdminUser;
1439
- resource: AdminForthResource;
1440
- meta: any;
1441
- source: ActionCheckSource;
1442
- adminforth: IAdminForth;
1443
- }) => boolean | Promise<boolean>);
1444
- export interface AdminForthResourceColumnInput extends Omit<AdminForthResourceColumnInputCommon, 'showIn' | 'backendOnly'> {
1445
- showIn?: ShowInInput;
1446
- foreignResource?: AdminForthForeignResource;
1447
- backendOnly?: BackendOnlyInput;
1448
- }
1449
- export interface AdminForthResourceColumn extends Omit<AdminForthResourceColumnCommon, 'showIn' | 'backendOnly'> {
1450
- showIn?: ShowIn;
1451
- foreignResource?: AdminForthForeignResource;
1452
- backendOnly?: BackendOnlyInput;
1453
- }
1454
- export interface IWebSocketClient {
1455
- id: string;
1456
- lastPing: number;
1457
- topics: Set<string>;
1458
- adminUser: AdminUser;
1459
- send: (message: string) => void;
1460
- close: () => void;
1461
- onMessage: (handler: (message: string) => void) => void;
1462
- onClose: (handler: () => void) => void;
1463
- }
1464
- export interface IWebSocketBroker {
1465
- publish: (topic: string, data: any, filterUsers?: (adminUser: AdminUser) => Promise<boolean>) => void;
1466
- registerWsClient: (client: IWebSocketClient) => void;
1467
- }
1468
- export {};
1469
- //# sourceMappingURL=Back.d.ts.map