Skip to content

Commit 044875c

Browse files
authored
Merge pull request #472 from devforth/next
Next
2 parents 7207eef + 2269d81 commit 044875c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

46 files changed

+1371
-780
lines changed

adapters/install-adapters.sh

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,8 @@ adminforth-email-adapter-mailgun adminforth-google-oauth-adapter adminforth-gith
44
adminforth-facebook-oauth-adapter adminforth-keycloak-oauth-adapter adminforth-microsoft-oauth-adapter \
55
adminforth-twitch-oauth-adapter adminforth-image-generation-adapter-openai adminforth-storage-adapter-amazon-s3 \
66
adminforth-storage-adapter-local adminforth-image-vision-adapter-openai adminforth-key-value-adapter-ram \
7-
adminforth-login-captcha-adapter-cloudflare adminforth-login-captcha-adapter-recaptcha adminforth-completion-adapter-google-gemini"
7+
adminforth-login-captcha-adapter-cloudflare adminforth-login-captcha-adapter-recaptcha adminforth-completion-adapter-google-gemini \
8+
adminforth-key-value-adapter-redis adminforth-key-value-adapter-leveldb"
89

910
# for each
1011
install_adapter() {
@@ -16,7 +17,7 @@ install_adapter() {
1617
git pull
1718
else
1819
echo "Repository for $adapter does not exist. Cloning..."
19-
git clone git@github.com:devforth/$adapter.git "$adapter"
20+
git clone https://github.com/devforth/$adapter.git "$adapter"
2021
cd "$adapter"
2122
fi
2223

adminforth/commands/createApp/templates/.env.local.hbs

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
ADMINFORTH_SECRET=123
22
NODE_ENV=development
3+
DEBUG_LEVEL=info
4+
AF_DEBUG_LEVEL=info
5+
DB_DEBUG_LEVEL=info
36
DATABASE_URL={{{dbUrl}}}
47
{{#if prismaDbUrl}}
58
PRISMA_DATABASE_URL={{{prismaDbUrl}}}
Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1-
import { Express } from "express";
1+
import { Express, Request, Response } from "express";
22
import { IAdminForth } from "adminforth";
3-
43
export function initApi(app: Express, admin: IAdminForth) {
54
app.get(`${admin.config.baseUrl}/api/hello/`,
6-
(req, res) => {
7-
res.json({ message: "Hello from AdminForth API!" });
5+
async (req: Request, res: Response) => {
6+
const allUsers = await admin.resource("adminuser").list([]);
7+
res.json({
8+
message: "Hello from AdminForth API!",
9+
users: allUsers,
10+
});
811
}
912
);
1013
}

adminforth/dataConnectors/postgres.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -385,7 +385,7 @@ class PostgresConnector extends AdminForthBaseConnector implements IAdminForthDa
385385
const tableName = resource.table;
386386
const result = {};
387387
await Promise.all(columns.map(async (col) => {
388-
const q = `SELECT MIN(${col.name}) as min, MAX(${col.name}) as max FROM "${tableName}"`;
388+
const q = `SELECT MIN("${col.name}") as min, MAX("${col.name}") as max FROM "${tableName}"`;
389389
dbLogger.trace(`🪲📜 PG Q: ${q}`);
390390
const stmt = await this.client.query(q);
391391
const { min, max } = stmt.rows[0];

adminforth/documentation/docs/tutorial/03-Customization/02-customFieldRendering.md

Lines changed: 91 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -233,6 +233,97 @@ Now you can use this component in the configuration of the resource:
233233
}
234234
```
235235
236+
### Custom record editing (updating other fields)
237+
238+
Sometimes a custom editor needs to update not only its own field, but also other fields of the record (for example, generate a slug from a title).
239+
240+
For this, custom `edit`/`create` components can emit an `update:recordFieldValue` event with the payload `{ fieldName, fieldValue }`. AdminForth will update the corresponding field in the record.
241+
242+
```html title='./custom/TitleWithSlugEditor.vue'
243+
<template>
244+
<div class="flex flex-col gap-2">
245+
<Input
246+
:model-value="record[column.name]"
247+
:placeholder="$t('Title')"
248+
@update:model-value="onTitleChange"
249+
/>
250+
<Input
251+
:model-value="record.slug"
252+
:placeholder="$t('Slug')"
253+
readonly
254+
/>
255+
</div>
256+
</template>
257+
258+
<script setup lang="ts">
259+
import Input from "@/afcl/Input.vue";
260+
import type {
261+
AdminForthResourceColumnCommon,
262+
AdminForthResourceCommon,
263+
AdminUser,
264+
} from "@/types/Common";
265+
266+
const props = defineProps<{
267+
column: AdminForthResourceColumnCommon;
268+
record: any;
269+
meta: any;
270+
resource: AdminForthResourceCommon;
271+
adminUser: AdminUser;
272+
readonly: boolean;
273+
}>();
274+
275+
const emit = defineEmits([
276+
"update:value", // update current column value
277+
"update:recordFieldValue", // update any other field in the record
278+
]);
279+
280+
function slugify(value: string) {
281+
return value
282+
?.toLowerCase()
283+
.trim()
284+
.replace(/[^a-z0-9]+/g, "-")
285+
.replace(/(^-|-$)+/g, "");
286+
}
287+
288+
function onTitleChange(newTitle: string) {
289+
// update current column value
290+
emit("update:value", newTitle);
291+
292+
// update another field in the record (e.g. slug)
293+
emit("update:recordFieldValue", {
294+
fieldName: "slug",
295+
fieldValue: slugify(newTitle),
296+
});
297+
}
298+
</script>
299+
```
300+
301+
And use it in the resource configuration for both `edit` and `create` views:
302+
303+
```ts title='./resources/apartments.ts'
304+
{
305+
...
306+
resourceId: 'aparts',
307+
columns: [
308+
...
309+
{
310+
name: 'title',
311+
components: {
312+
edit: '@@/TitleWithSlugEditor.vue',
313+
create: '@@/TitleWithSlugEditor.vue',
314+
},
315+
},
316+
{
317+
name: 'slug',
318+
// standard input; value will be kept in sync
319+
...
320+
},
321+
...
322+
],
323+
...
324+
}
325+
```
326+
236327
### Custom inValidity inside of the custom create/edit components
237328
238329
Custom componets can emit `update:inValidity` event to parent to say that the field is invalid.

adminforth/documentation/docs/tutorial/05-ListOfAdapters.md

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -244,10 +244,52 @@ The RAM adapter is a simplest in-memory key-value storage. Stores data in proces
244244

245245
Pros:
246246
* Simplest in use - does not reqauire any external daemon.
247+
247248
Cones:
248249
* In production sutable for single-process installations only
249250

250251

252+
### Redis adapter
253+
254+
```bash
255+
npm i @adminforth/key-value-adapter-redis
256+
```
257+
258+
Redis adapter uses in-memory RAM-based Redis database with O(1) get complexity. It is great fit for most of lightweight tasks which fit in RAM. Also capable with multi-process or replica-based installations as centralized storage. Please note that Redis daemon might be not persisted to disk during restarts without additional settings, so if persistence is critical for your task - you might need to set up it separately (for many tasks like rate-limits ephemeral data are fine
259+
260+
261+
```ts
262+
import RedisKeyValueAdapter from '@adminforth/key-value-adapter-redis';
263+
264+
const adapter = new RedisKeyValueAdapter({
265+
redisUrl: '127.0.0.1:6379'
266+
})
267+
268+
adapeter.set('test-key', 'test-value', 120); //expiry in 120 seconds
269+
270+
```
271+
272+
### LevelDB adapter
273+
274+
```bash
275+
npm i @adminforth/key-value-adapter-leveldb
276+
```
277+
278+
LebelDB uses disk storage with o(log(n)) get complexity. Good fit for large and/or persistent KV datasets which still require fast KV access but don't efficently fit into RAM. Please not that this is a single-process adapter only, so if you will run severall processes of admin - they will not be able to work with this adapter (>=2 processes which look at same level database might lead to unpredicted behaviour - exceptions or crashes).
279+
280+
You can use replicas with isolated disks, however in this case state will be also separated between replicas.
281+
282+
```ts
283+
import LevelDBKeyValueAdapter from '@adminforth/key-value-adapter-leveldb'
284+
285+
const adapter = new LevelDBKeyValueAdapter({
286+
dbPath: './testdb'
287+
});
288+
289+
adapeter.set('test-key', 'test-value', 120); //expiry in 120 seconds
290+
291+
```
292+
251293
## 🤖Captcha adapters
252294

253295
Used to add capthca to the login screen

adminforth/documentation/docs/tutorial/08-Plugins/02-TwoFactorsAuth.md

Lines changed: 3 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -280,10 +280,6 @@ options: {
280280
adminUser: adminUser,
281281
//diff-add
282282
userPk: adminUser.pk,
283-
//diff-add
284-
cookies: extra.cookies,
285-
//diff-add
286-
response: response,
287283
//diff-add
288284
extra: extra,
289285
//diff-add
@@ -393,8 +389,6 @@ hooks: {
393389
const verifyRes = await t2fa.verify(confirmationResult, {
394390
adminUser,
395391
userPk: adminUser.pk,
396-
cookies: extra?.cookies,
397-
response,
398392
extra
399393
});
400394
if (!verifyRes || 'error' in verifyRes) {
@@ -404,7 +398,7 @@ hooks: {
404398
},
405399
},
406400
create: {
407-
beforeSave: async ({ adminUser, adminforth, extra }) => {
401+
beforeSave: async ({ adminUser, adminforth, response, extra }) => {
408402
const t2fa = adminforth.getPluginByClassName('TwoFactorsAuthPlugin');
409403
if (!t2fa) {
410404
return { ok: false, error: 'TwoFactorsAuthPlugin is not configured' };
@@ -418,7 +412,7 @@ hooks: {
418412
const verifyRes = await t2fa.verify(confirmationResult, {
419413
adminUser,
420414
userPk: adminUser.pk,
421-
cookies: extra?.cookies,
415+
extra
422416
});
423417
if (!verifyRes || 'error' in verifyRes) {
424418
return { ok: false, error: verifyRes?.error || 'Two-factor verification failed' };
@@ -534,12 +528,8 @@ app.post(`${ADMIN_BASE_URL}/myCriticalAction`,
534528
adminUser: adminUser,
535529
// diff-add
536530
userPk: adminUser.pk,
537-
// diff-add
538-
cookies: cookies,
539-
//diff-add
540-
response: res,
541531
//diff-add
542-
extra: {...req.headers},
532+
extra: {...req.headers, ...req.cookies, response: res},
543533
//diff-add
544534
});
545535
// diff-add

adminforth/documentation/docs/tutorial/08-Plugins/04-RichEditor.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -145,7 +145,7 @@ To get completion suggestions for the text in the editor, you can use the `compl
145145

146146
![alt text](gptDemo.gif)
147147

148-
### Imges in Rich editor
148+
### Images in Rich editor
149149

150150
First, you need to create resource for images:
151151
```prisma title="schema.prisma"

adminforth/documentation/docs/tutorial/08-Plugins/05-upload.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -305,6 +305,73 @@ new UploadPlugin({
305305
> adminServeBaseUrl defines the public path prefix. If your AdminForth base URL is /admin, files will be accessible under /admin/static/source/&lt;key&gt;.
306306
307307
308+
## API
309+
310+
### uploadFromBufferToNewRecord
311+
312+
In some cases you may want to upload a file directly from your backend (for example, a file generated by a background job or received from a webhook) without going through the browser. For this, the Upload plugin exposes the `uploadFromBufferToNewRecord` method.
313+
314+
You can code it as custom logic or you can simply reuse Upload plugin for this purpose as well.
315+
316+
This method uploads a file from a Node.js `Buffer`, automatically creates a record in the corresponding resource, and returns both the stored file path and a preview URL.
317+
318+
```ts title="./some-backend-service.ts"
319+
import { admin } from './admin'; // your AdminForth instance
320+
321+
...
322+
plugins: [
323+
new UploadPlugin({
324+
id: 'my_reports_plugin', // unique identifier for your plugin instance
325+
....
326+
})
327+
]
328+
...
329+
330+
const plugin = admin.getPluginById('my_reports_plugin');
331+
332+
const { path, previewUrl } = await plugin.uploadFromBufferToNewRecord({
333+
filename: 'report.pdf',
334+
contentType: 'application/pdf',
335+
buffer, // Node.js Buffer with file content
336+
adminUser, // current admin user or system user
337+
recordAttributes: {
338+
title: 'Generated report',
339+
listed: false,
340+
},
341+
});
342+
```
343+
344+
- `uploadFromBufferToNewRecord` uses the configured storage adapter (S3, local, etc.) to store the file.
345+
- It automatically creates a new record in the resource and stores the file path into the column defined by `pathColumnName`, together with any extra `recordAttributes` you pass.
346+
- It returns an object `{ path, previewUrl }`, where `previewUrl` is the same URL that would be used for previews inside AdminForth.
347+
348+
> ⚠️ It is not recommended to upload large files from the backend using `uploadFromBuffer`, because the entire file must go through your server memory and network. For large uploads you should prefer frontend presigned uploads directly to storage. You can find an example of presigned upload flow using upload plugin in the Rich editor plugin source code (Rich editor actually uses Upload plugin to upload images in edited content).
349+
350+
351+
### uploadFromBufferToExistingRecord
352+
353+
If you already have a record and just want to replace the file referenced in its `pathColumnName` field, you can use the `uploadFromBufferToExistingRecord` method. It uploads a file from a Node.js `Buffer`, updates the existing record, and returns the new file path and preview URL.
354+
355+
```ts title="./some-backend-service.ts"
356+
const plugin = admin.getPluginById('my_reports_plugin');
357+
358+
const { path, previewUrl } = await plugin.uploadFromBufferToExistingRecord({
359+
recordId: existingRecordId, // primary key of the record to update
360+
filename: 'report.pdf',
361+
contentType: 'application/pdf',
362+
buffer, // Node.js Buffer with file content
363+
adminUser, // current admin user or system user
364+
extra: {}, // optional extra meta for your hooks / audit
365+
});
366+
```
367+
368+
- Uses the same storage adapter and validation rules as `uploadFromBufferToNewRecord` (file extension whitelist, `maxFileSize`, `filePath` callback, etc.).
369+
- Does not create a new record – it only updates the existing one identified by `recordId`, replacing the value in `pathColumnName` with the new storage path.
370+
- If the generated `filePath` would be the same as the current value in the record, it throws an error to help you avoid CDN/browser caching issues. To force a refresh, make sure your `filePath` callback produces a different key (for example, include a timestamp or random UUID).
371+
372+
> ⚠️ The same recommendation about large files applies here: avoid using `uploadFromBufferToExistingRecord` for very large uploads; prefer a presigned upload flow from the frontend instead.
373+
374+
308375
309376
## Image generation
310377

adminforth/documentation/docs/tutorial/08-Plugins/14-markdown.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,7 @@ Here is how it looks in show view:
3737
![alt text](markdown-show1.png)
3838
![alt text](markdown-show2.png)
3939

40-
### Imges in Markdown
40+
### Images in Markdown
4141

4242
First, you need to create resource for images:
4343
```prisma title="schema.prisma"

0 commit comments

Comments
 (0)