### Install and Use Node.js Version 20 Source: https://adminforth.dev/docs/tutorial/gettingStarted Installs Node.js version 20, sets it as the default, and switches to it. This ensures the correct Node.js environment for AdminForth. ```bash nvm install 20 nvm alias default 20 nvm use 20 ``` -------------------------------- ### Install Node Version Manager (NVM) Source: https://adminforth.dev/docs/tutorial/hello-world Installs and sets the default Node.js version to v20 using NVM. This is a prerequisite for the project setup. ```bash nvm install 20 nvm alias default 20 nvm use 20 ``` -------------------------------- ### Initialize Database with Prisma Source: https://adminforth.dev/docs/tutorial/gettingStarted Creates the initial database schema and applies it using Prisma. This command is typically run after project creation to set up the database structure. ```bash npm run makemigration -- --name init ``` -------------------------------- ### Run AdminForth Server Source: https://adminforth.dev/docs/tutorial/gettingStarted Starts the AdminForth development server. After running this command, the application can be accessed via a web browser. ```bash npm start ``` -------------------------------- ### Integrate Mailgun Adapter with EmailInvitePlugin Source: https://adminforth.dev/docs/tutorial/Plugins/email-invite This example shows how to install the Mailgun adapter for AdminForth and configure the `EmailInvitePlugin` to use it. It requires installing the `@adminforth/email-adapter-mailgun` package and providing Mailgun API credentials and domain information via environment variables. ```typescript import EmailAdapterMailgun from "@adminforth/email-adapter-mailgun"; ... plugins: [ new EmailInvitePlugin({ emailField: 'email', passwordField: 'password', sendFrom: 'noreply@yourapp.com', adapter: new EmailAdapterMailgun({ apiKey: process.env.MAILGUN_API_KEY as string, domain: process.env.MAILGUN_DOMAIN as string, baseUrl: process.env.MAILGUN_REGION_URL as string, }), }), ], ``` -------------------------------- ### Install Open Signup Plugin Source: https://adminforth.dev/docs/tutorial/Plugins/open-signup Installs the Open Signup plugin using npm. This is the first step to enable self-registration in Adminforth. ```bash npm install @adminforth/open-signup --save ``` -------------------------------- ### Install and Configure Local Storage Adapter Source: https://adminforth.dev/docs/tutorial/Plugins/05-0-upload This example demonstrates how to install and configure the `@adminforth/storage-adapter-local` for AdminForth. It sets up the UploadPlugin to store files on the server's filesystem, specifying the folder, base URL for serving files, and access mode (public or private). ```bash npm i @adminforth/storage-adapter-local --save ``` ```typescript import LocalStorageAdapter from '@adminforth/storage-adapter-local'; import { UploadPlugin } from "@adminforth/upload-plugin"; import { randomUUID } from "crypto"; new UploadPlugin({ storageAdapter: new LocalStorageAdapter({ fileSystemFolder: "./db/uploads", adminServeBaseUrl: "static/source", mode: "public", // or "private" signingSecret: process.env.ADMINFORTH_SECRET, }), pathColumnName: 'apartment_image', allowedFileExtensions: ['jpg', 'jpeg', 'png', 'gif', 'webm', 'webp'], maxFileSize: 1024 * 1024 * 20, // 20 MB filePath: ({originalFilename, originalExtension, contentType}) => `aparts/${new Date().getFullYear()}/${randomUUID()}-${originalFilename}.${originalExtension}`, }) ``` -------------------------------- ### Create AdminForth App Interactively Source: https://adminforth.dev/docs/tutorial/gettingStarted Initiates the creation of a new AdminForth application by prompting the user for necessary information. This method allows for interactive configuration. ```bash npx adminforth create-app ``` -------------------------------- ### Create and Apply Prisma Migration Source: https://adminforth.dev/docs/tutorial/gettingStarted This command sequence is used to create a new database migration for the 'apartments' model and then apply it locally. It involves running 'npm run makemigration' with a descriptive name and then executing 'npm run migrate:local' to update the database schema. ```bash npm run makemigration -- --name add-apartments ; npm run migrate:local ``` -------------------------------- ### Install Two-Factor Authentication Plugin Source: https://adminforth.dev/docs/tutorial/Plugins/TwoFactorsAuth Installs the Two-Factor Authentication Plugin using npm. This is the initial step to integrate the plugin into your project. ```bash npm i @adminforth/two-factors-auth --save ``` -------------------------------- ### Initialize Admin User and Seed Data (TypeScript) Source: https://adminforth.dev/docs/tutorial/gettingStarted This TypeScript code snippet demonstrates the initialization logic for an AdminForth project. It discovers databases, creates an 'adminuser' if it doesn't exist (with a default password hash), and then calls the `seedDatabase` function to populate the 'aparts' resource. This ensures a basic setup for the admin interface upon first launch. ```typescript if (fileURLToPath(import.meta.url) === path.resolve(process.argv[1])) { ... admin.discoverDatabases().then(async () => { if (!await admin.resource('adminuser').get([Filters.EQ('email', 'adminforth')])) { await admin.resource('adminuser').create({ email: 'adminforth', password_hash: await AdminForth.Utils.generatePasswordHash('adminforth'), role: 'superadmin', }); } await seedDatabase(); }); ``` -------------------------------- ### Navigate to Project Directory Source: https://adminforth.dev/docs/tutorial/gettingStarted Changes the current directory to the newly created AdminForth project folder. Replace 'myadmin' with the actual project name provided during creation. ```bash cd myadmin ``` -------------------------------- ### Create and Apply Database Migrations Source: https://adminforth.dev/docs/tutorial/gettingStarted Generates a new database migration file based on changes in the Prisma schema and applies it to the database. This is used for subsequent schema updates. ```bash npm run makemigration -- --name init ; npm run migrate:local ``` -------------------------------- ### Install Key-Value Adapter (NPM) Source: https://adminforth.dev/docs/tutorial/Plugins/TwoFactorsAuth Installs the in-memory Key-Value adapter for AdminForth using npm. This adapter is required for the Two-Factor Authentication plugin when integrating passkeys. ```bash npm i @adminforth/key-value-adapter-ram ``` -------------------------------- ### Install Email Invite Plugin Source: https://adminforth.dev/docs/tutorial/Plugins/email-invite Installs the Email Invite plugin using npm. This is a prerequisite for using the plugin's functionality. ```bash npm install @adminforth/email-invite --save ``` -------------------------------- ### Install AdminForth i18n and OpenAI Completion Adapter Source: https://adminforth.dev/docs/tutorial/Plugins/i18n Installs the necessary AdminForth i18n plugin and the OpenAI Chat GPT completion adapter using npm. These packages are essential for enabling internationalization and AI-powered translations. ```bash npm install @adminforth/i18n --save npm install @adminforth/completion-adapter-open-ai-chat-gpt --save ``` -------------------------------- ### Install OpenAI Completion Adapter Source: https://adminforth.dev/docs/tutorial/ListOfAdapters Installs the OpenAI Completion Adapter for AdminForth. This adapter integrates with OpenAI’s ChatGPT models for AI-powered text completion and conversational features. ```bash npm i @adminforth/completion-adapter-open-ai-chat-gpt ``` -------------------------------- ### Install AWS SES Email Adapter Source: https://adminforth.dev/docs/tutorial/Plugins/open-signup Installs the AWS SES email adapter package, which is used by the Open Signup plugin for sending email verification emails. ```bash npm i @adminforth/email-adapter-aws-ses --save ``` -------------------------------- ### Install Inline Create Plugin with npm Source: https://adminforth.dev/docs/tutorial/Plugins/inline-create This snippet shows the command to install the Inline Create plugin using npm. It is a direct dependency for using the plugin's functionality. ```bash npm install @adminforth/inline-create --save ``` -------------------------------- ### Install AdminForth Markdown Plugin Source: https://adminforth.dev/docs/tutorial/Plugins/markdown Installs the Markdown plugin using npm. This is the first step to enable Markdown support in your AdminForth project. ```bash npm install @adminforth/markdown --save ``` -------------------------------- ### Install Bulk AI Flow Plugin Source: https://adminforth.dev/docs/tutorial/Plugins/bulk-ai-flow Installs the Bulk AI Flow plugin using npm. This is a prerequisite for using the plugin's features. ```bash npm install @adminforth/bulk-ai-flow --save ``` -------------------------------- ### Install Foreign Inline Show Plugin Source: https://adminforth.dev/docs/tutorial/Plugins/ForeignInlineShow Installs the ForeignInlineShow plugin using npm. This is the initial step to integrate the plugin into your project. ```bash npm i @adminforth/foreign-inline-show --save ``` -------------------------------- ### Install and Link AdminForth ChatGPT Plugin Locally Source: https://adminforth.dev/docs/tutorial/Advanced/plugin-development Instructions for installing the ChatGPT plugin locally using npm link for development. This involves linking the plugin directory to your AdminForth project to enable local testing before publishing. ```bash cd af-plugin-chatgpt npm link cd ../your-adminforth-project npm link af-plugin-chatgpt ``` -------------------------------- ### Install OpenAI Image Generation Adapter Source: https://adminforth.dev/docs/tutorial/Plugins/05-0-upload Installs the necessary npm package for integrating OpenAI's image generation models with Admin Forth. ```bash npm i @adminforth/image-generation-adapter-openai ``` -------------------------------- ### Install Image Vision Adapter (OpenAI) Source: https://adminforth.dev/docs/tutorial/Plugins/bulk-ai-flow Installs the OpenAI image vision adapter, which is required for vision-related functionalities within the Bulk AI Flow plugin. ```bash npm install @adminforth/image-vision-adapter-openai --save ``` -------------------------------- ### Install GitHub OAuth Adapter Source: https://adminforth.dev/docs/tutorial/ListOfAdapters Installs the GitHub OAuth Adapter for AdminForth. This adapter enables authentication via GitHub accounts, useful for developer tools and open-source applications. ```bash npm i @adminforth/github-oauth-adapter ``` -------------------------------- ### Install AdminForth OAuth Plugin and Google Adapter Source: https://adminforth.dev/docs/tutorial/Plugins/oauth Installs the core AdminForth OAuth plugin and the specific adapter for Google OAuth using npm. These are essential for enabling OAuth authentication. ```bash npm install @adminforth/oauth --save npm install @adminforth/google-oauth-adapter --save # for Google OAuth ``` -------------------------------- ### Install Google Gemini Completion Adapter Source: https://adminforth.dev/docs/tutorial/ListOfAdapters Installs the Google Gemini Completion Adapter for AdminForth. This adapter integrates with Google Gemini models for AI-powered text completion and conversational features. ```bash npm i @adminforth/completion-adapter-google-gemini ``` -------------------------------- ### Install Universal Search Plugin with npm Source: https://adminforth.dev/docs/tutorial/Plugins/universal-filters This command installs the Universal Search plugin for AdminForth using npm. It is a required step before integrating the plugin into your project. ```bash npm i @adminforth/universal-search --save ``` -------------------------------- ### Initialize and Install Project Dependencies Source: https://adminforth.dev/docs/tutorial/hello-world Creates a new project directory, initializes a Node.js project with npm, installs necessary AdminForth and development dependencies, and initializes TypeScript configuration. ```bash mkdir af-hello cd af-hello npm init -y npm i adminforth express @dotenvx/dotenvx @types/express typescript tsx @types/node -D npx --yes tsc --init --module NodeNext --target ESNext ``` -------------------------------- ### Register Apartments Resource in AdminForth (TypeScript) Source: https://adminforth.dev/docs/tutorial/gettingStarted Imports the configured 'apartments' resource and registers it within the AdminForth application. This step makes the resource available in the admin interface, including its menu item and associated actions. It demonstrates how to add custom resources to the AdminForth setup. ```typescript import { AdminForth } from 'adminforth'; import apartmentsResource from "./resources/apartments.js"; import usersResource from "./resources/users.js"; export const admin = new AdminForth({ // ... other configurations resources: [ usersResource, apartmentsResource, ], menu: [ { label: 'Core', icon: 'flowbite:brain-solid', open: true, children: [ { homepage: true, label: 'Apartments', icon: 'flowbite:home-solid', resourceId: 'aparts', }, ] }, { type: 'gap' }, { type: 'divider' }, { type: 'heading', label: 'SYSTEM' }, { label: 'Users', // ... other user menu configurations } ], // ... other configurations }); ``` -------------------------------- ### Example: Setting an Icon for a Menu Item Source: https://adminforth.dev/docs/api/Common/interfaces/AdminForthConfigMenuItem Shows how to assign an icon to a menu item using the Iconify format. The format is ':'. ```javascript { icon: 'flowbite:brain-solid' } ``` -------------------------------- ### Initialize npm and Install Dependencies (Shell) Source: https://adminforth.dev/docs/tutorial/Advanced/plugin-development Commands to initialize a new npm package in the plugin's custom frontend directory and install the 'vue-suggestion-input' package as a development dependency. This sets up the frontend environment for the custom component. ```shell cd af-plugin-chatgpt/custom npm init -y npm i vue-suggestion-input -D ``` -------------------------------- ### Configure AdminForth Resources and Start Server (Node.js) Source: https://adminforth.dev/docs/tutorial/hello-world This snippet demonstrates how to configure AdminForth resources like 'posts' and 'users', bundle the SPA, and start the Express server. It includes logic to create a default admin user if none exists. Dependencies include 'express' and 'AdminForth'. ```javascript if (import.meta.url === `file://${process.argv[1]}`) { const app = express() app.use(express.json()); const port = 3500; admin.bundleNow({ hotReload: process.env.NODE_ENV === 'development' }).then(() => { logger.info('Bundling AdminForth SPA done.'); }); admin.express.serve(app) admin.discoverDatabases().then(async () => { if (await admin.resource('adminuser').count() === 0) { await admin.resource('adminuser').create({ email: 'adminforth', passwordHash: await AdminForth.Utils.generatePasswordHash('adminforth'), role: 'superadmin', }); } }); admin.express.listen(port, () => { logger.info(`\n⚡ AdminForth is available at http://localhost:${port}\n`) }); } ``` -------------------------------- ### Install Local Storage Adapter Source: https://adminforth.dev/docs/tutorial/ListOfAdapters Installs the Local Storage Adapter for AdminForth. This adapter stores files locally on the server’s filesystem, suitable for development or small-scale setups. ```bash npm i @adminforth/storage-adapter-local ``` -------------------------------- ### Basic Open Signup Plugin Usage Source: https://adminforth.dev/docs/tutorial/Plugins/open-signup Demonstrates how to import and instantiate the Open Signup plugin in an Adminforth user resource configuration. ```typescript import OpenSignupPlugin from '@adminforth/open-signup'; new OpenSignupPlugin({ emailField: 'email', passwordField: 'password', passwordHashField: 'password_hash', defaultFieldValues: { role: 'user', }, }), ``` -------------------------------- ### Defining Bulk Action with Allowed Check Example Source: https://adminforth.dev/docs/api/Back/interfaces/AdminForthBulkAction This example demonstrates how to configure bulk actions, including a custom 'Mark as read' action. The `allowed` property within the bulk action configuration leverages the `allowedActions` resolved permissions, showing how to conditionally enable actions based on user roles or other criteria. ```javascript options: { bulkActions: [ { label: 'Mark as read', action: async ({ resource, recordIds }) => { await markAsRead(recordIds); }, allowed: ({ allowedActions }) => allowedActions.edit, } ], allowedActions: { edit: ({ resource, adminUser, recordIds }) => { return adminUser.dbUser.role === 'superadmin'; } } } ``` -------------------------------- ### Enable User Prompt Editing in Plugin Setup Source: https://adminforth.dev/docs/tutorial/Plugins/bulk-ai-flow Allows users to customize generation prompts by adding `askConfirmationBeforeGenerating: true` to the plugin setup. This presents users with 'Start generation' and 'Edit prompts' buttons. Updated prompts are stored in local storage and are specific to the browser. ```javascript ... askConfirmationBeforeGenerating: true, ... ``` -------------------------------- ### Initialize Custom Components Directory (Bash) Source: https://adminforth.dev/docs/tutorial/hello-world This command sequence shows how to create and initialize a 'custom' directory for custom AdminForth components using npm. It guides the user to navigate into the directory and run 'npm init -y'. ```bash cd ./custom npm init -y ``` -------------------------------- ### Get Response Status Code (Node.js) Source: https://adminforth.dev/docs/api/Back/interfaces/IAdminUserExpressRequest Retrieve the 3-digit HTTP response status code. This property is optional and only valid for responses obtained from a ClientRequest. Example: 404. ```javascript const statusCode = response.statusCode; console.log(`Status Code: ${statusCode}`); ``` -------------------------------- ### Execute Prisma Database Migrations Source: https://adminforth.dev/docs/tutorial/hello-world Commands to create and apply database migrations using Prisma. It first deploys existing migrations and then sets up a new development migration. ```bash npm run makemigration --name init ; npm run migrate:local ``` -------------------------------- ### Example: Setting a Custom Component for a Page Menu Item Source: https://adminforth.dev/docs/api/Common/interfaces/AdminForthConfigMenuItem Demonstrates how to specify a custom Vue.js component for a menu item of type PAGE. The component path should be prefixed with '@@/'. ```javascript { component: '@@/Dashboard.vue' } ``` -------------------------------- ### Initialize AdminForth Application with TypeScript Source: https://adminforth.dev/docs/tutorial/hello-world This snippet demonstrates the basic setup for an AdminForth application using TypeScript. It initializes the AdminForth instance with configuration for authentication, data sources, and resource definitions for 'adminuser' and 'posts'. ```typescript import express from 'express'; import AdminForth, { AdminForthDataTypes, Filters, logger } from 'adminforth'; import type { AdminForthResourceInput, AdminForthResource, AdminUser } from 'adminforth'; export const admin = new AdminForth({ baseUrl: '', auth: { usersResourceId: 'adminuser', // resource to get user during login usernameField: 'email', // field where username is stored, should exist in resource passwordHashField: 'passwordHash', }, customization: { brandName: 'My Admin', datesFormat: 'D MMM YY', timeFormat: 'HH:mm:ss', emptyFieldPlaceholder: '-', }, dataSources: [{ id: 'maindb', url: `sqlite://${process.env.DATABASE_FILE}`, }], resources: [ { dataSource: 'maindb', table: 'adminuser', resourceId: 'adminuser', label: 'Users', recordLabel: (r: any) => `👤 ${r.email}`, columns: [ { name: 'id', primaryKey: true, fillOnCreate: () => Math.random().toString(36).substring(7), showIn: { edit: false, create: false, }, }, { name: 'email', required: true, isUnique: true, enforceLowerCase: true, validation: [ AdminForth.Utils.EMAIL_VALIDATOR, ] }, { name: 'createdAt', type: AdminForthDataTypes.DATETIME, showIn: { edit: false, create: false, }, fillOnCreate: () => (new Date()).toISOString(), }, { name: 'role', enum: [ { value: 'superadmin', label: 'Super Admin' }, { value: 'user', label: 'User' }, ] }, { name: 'password', virtual: true, required: { create: true }, editingNote: { edit: 'Leave empty to keep password unchanged' }, minLength: 8, type: AdminForthDataTypes.STRING, showIn: { show: false, list: false, filter: false, }, masked: true, }, { name: 'passwordHash', backendOnly: true, showIn: { all: false } } ], hooks: { create: { beforeSave: async ({ record, adminUser, resource }: { record: any, adminUser: AdminUser, resource: AdminForthResource }) => { record.password_hash = await AdminForth.Utils.generatePasswordHash(record.password); return { ok: true }; } }, edit: { beforeSave: async ({ oldRecord, updates, adminUser, resource }: { oldRecord: any, updates: any, adminUser: AdminUser, resource: AdminForthResource }) => { logger.info('Updating user', updates); if (oldRecord.id === adminUser.dbUser.id && updates.role) { return { ok: false, error: 'You cannot change your own role' }; } if (updates.password) { updates.password_hash = await AdminForth.Utils.generatePasswordHash(updates.password); } return { ok: true } }, }, } }, { table: 'post', resourceId: 'posts', dataSource: 'maindb', label: 'Posts', recordLabel: (r: any) => `📝 ${r.title}`, columns: [ { name: 'id', primaryKey: true, fillOnCreate: () => Math.random().toString(36).substring(7), showIn: { edit: false, create: false, }, }, { name: 'title', type: AdminForthDataTypes.STRING, required: true, showIn: { all: true }, maxLength: 255, minLength: 3, }, { name: 'content', showIn: { all: true }, }, { name: 'createdAt', showIn: { edit: false, create: false, }, fillOnCreate: () => (new Date()).toISOString(), }, { name: 'published', required: true, }, { name: 'authorId', foreignResource: { resourceId: 'adminuser', }, showIn: { edit: false, create: false, }, fillOnCreate: ({ adminUser }: { adminUser: AdminUser }) => { return adminUser.dbUser.id; } } ], } ], menu: [ { label: 'Core', ``` -------------------------------- ### Get Response Status Message (Node.js) Source: https://adminforth.dev/docs/api/Back/interfaces/IAdminUserExpressRequest Retrieve the HTTP response status message, also known as the reason phrase. This property is optional and only valid for responses obtained from a ClientRequest. Example: 'OK' or 'Internal Server Error'. ```javascript const statusMessage = response.statusMessage; console.log(`Status Message: ${statusMessage}`); ``` -------------------------------- ### Configure Demo Mode Credentials Source: https://adminforth.dev/docs/api/Back/interfaces/AdminForthConfig Provides a login and password pair for demo mode. This is for demonstration purposes only and should not be used in production environments. Format: 'login:password'. ```typescript demoCredentials: 'demo:password123' ``` -------------------------------- ### Use CompletionAdapter in Plugin Handler Source: https://adminforth.dev/docs/tutorial/Advanced/plugin-development This TypeScript example illustrates how to use the configured CompletionAdapter within a plugin's handler function. It calls the `complete` method of the adapter to get content completion based on provided parameters and plugin options. ```typescript handler: async (a) => { ... const resp = await this.options.adapter.complete(content, ['.'], this.options.expert?.maxTokens || 50); ... } ``` -------------------------------- ### Define npm Scripts for Development and Migrations Source: https://adminforth.dev/docs/tutorial/hello-world Adds essential scripts to `package.json` for running the application with hot-reloading, managing environment variables, and performing database migrations using Prisma. ```json { ... "type": "module", "scripts": { ... "env": "dotenvx run -f .env.local -f .env --overload --", "start": "npm run env -- tsx watch index.ts", "migrateLocal": "npm run env -- npx prisma migrate deploy", "makemigration": "npm run env -- npx --yes prisma migrate deploy; npm run env -- npx --yes prisma migrate dev" } } ``` -------------------------------- ### Import and Initialize AdminForth Source: https://adminforth.dev/docs/tutorial/Customization/dataApi Demonstrates how to import necessary components from the 'adminforth' package and initialize the AdminForth instance for data manipulation. ```javascript import { Filters, Sorts } from 'adminforth'; const admin = new AdminForth({ ... }); ``` -------------------------------- ### Bypass WebSocket Subscription Authorization with /opentopic/ (TypeScript) Source: https://adminforth.dev/docs/tutorial/Customization/websocket This example illustrates how topics starting with `/opentopic/` bypass the `websocketTopicAuth` check, allowing any user to subscribe. This is used internally by AdminForth for features like menu badges. This bypass is important to be aware of when implementing custom authorization logic. ```typescript if (topic.startsWith('/opentopic/')) { // Allow subscription bypassing websocketTopicAuth return true; } ``` -------------------------------- ### Frontend Save Interceptor for 2FA Confirmation (Vue) Source: https://adminforth.dev/docs/tutorial/Plugins/TwoFactorsAuth This Vue component, injected via `pageInjections`, intercepts save actions ('create' or 'edit') to prompt the user for 2FA confirmation. It utilizes the `adminforthTwoFaModal` to get the confirmation result and passes it to the backend. Ensure `@adminforth/two-factors-auth` is installed and instantiated. ```vue ``` -------------------------------- ### Define Prisma Model for Apartments Source: https://adminforth.dev/docs/tutorial/gettingStarted This snippet shows how to define a new Prisma model named 'apartments' in the schema.prisma file. It includes various fields such as id, created_at, title, square_meter, price, number_of_rooms, description, country, listed, and realtor_id, specifying their data types and constraints. ```prisma model apartments { id String @id created_at DateTime? title String square_meter Float? price Decimal number_of_rooms Int? description String? country String? listed Boolean realtor_id String? } ``` -------------------------------- ### Create Custom Three Dots Menu Item Component Source: https://adminforth.dev/docs/tutorial/Customization/pageInjections A Vue component to be added to the three dots menu. This example component calculates and displays the reading time of a description field. It uses the `text-analyzer` package and AdminForth's API for alerts and closing the dropdown. Ensure `text-analyzer` is installed (`npm i text-analyzer` in the `custom` directory). ```html ``` -------------------------------- ### get() - Get request header Source: https://adminforth.dev/docs/api/Back/interfaces/IAdminUserExpressRequest The `get()` method retrieves the value of a specified request header. It is case-insensitive and handles the 'Referrer' and 'Referer' headers interchangeably. ```APIDOC ## get() ### Description Return request header. The `Referrer` header field is special-cased, both `Referrer` and `Referer` are interchangeable. ### Method `get(name)` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript req.get('Content-Type'); // => "text/plain" req.get('content-type'); // => "text/plain" req.get('Something'); // => undefined ``` ### Response #### Success Response (200) - **string[]** - An array of strings representing the header value(s), or `undefined` if the header is not found. #### Response Example ```json { "example": "["text/plain"] or undefined" } ``` ### Aliased as `req.header()` ``` -------------------------------- ### Configure Apartments Resource (TypeScript) Source: https://adminforth.dev/docs/tutorial/gettingStarted Defines the 'apartments' resource for AdminForth, specifying data source, table name, labels, and detailed configurations for each column. It includes primary key, required fields, data types, input constraints, default values on creation, and foreign key relationships. This configuration enables CRUD operations and advanced filtering for apartment data. ```typescript import { AdminForthDataTypes, AdminForthResourceInput } from 'adminforth'; export default { dataSource: 'maindb', table: 'apartments', resourceId: 'aparts', // resourceId is defaulted to table name but you can redefine it like this e.g. // in case of same table names from different data sources label: 'Apartments', // label is defaulted to table name but you can change it recordLabel: (r) => `🏡 ${r.title}`, columns: [ { name: 'id', type: AdminForthDataTypes.STRING, label: 'Identifier', // if you wish you can redefine label, defaulted to uppercased name showIn: { // show column in filter and in show page list: false, edit: false, create: false, }, primaryKey: true, fillOnCreate: ({ initialRecord, adminUser }) => Math.random().toString(36).substring(7), // called during creation to generate content of field, initialRecord is values user entered, adminUser object of user who creates record }, { name: 'title', required: true, showIn: { all: true }, // all available options type: AdminForthDataTypes.STRING, maxLength: 255, // you can set max length for string fields minLength: 3, // you can set min length for string fields }, { name: 'created_at', type: AdminForthDataTypes.DATETIME, allowMinMaxQuery: true, showIn: { create: false }, fillOnCreate: ({ initialRecord, adminUser }) => (new Date()).toISOString(), }, { name: 'price', inputSuffix: 'USD', // you can add a suffix to an input field that will be displayed when creating or editing records allowMinMaxQuery: true, // use better experience for filtering e.g. date range, set it only if you have index on this column or if you sure there will be low number of rows editingNote: 'Price is in USD', // you can put a note near field on editing or creating page }, { name: 'square_meter', label: 'Square', allowMinMaxQuery: true, minValue: 1, // you can set min /max value for number columns so users will not be able to enter more/less maxValue: 1000, }, { name: 'number_of_rooms', allowMinMaxQuery: true, enum: [ { value: 1, label: '1 room' }, { value: 2, label: '2 rooms' }, { value: 3, label: '3 rooms' }, { value: 4, label: '4 rooms' }, { value: 5, label: '5 rooms' }, ], }, { name: 'description', sortable: false, showIn: { list: false }, }, { name: 'country', enum: [{ value: 'US', label: 'United States' }, { value: 'DE', label: 'Germany' }, { value: 'FR', label: 'France' }, { value: 'GB', label: 'United Kingdom' }, { value: 'NL', label: 'Netherlands' }, { value: 'IT', label: 'Italy' }, { value: 'ES', label: 'Spain' }, { value: 'DK', label: 'Denmark' }, { value: 'PL', label: 'Poland' }, { value: 'UA', label: 'Ukraine' }, { value: null, label: 'Not defined' }], }, { name: 'listed', required: true, // will be required on create/edit }, { name: 'realtor_id', foreignResource: { resourceId: 'adminuser', searchableFields: ["id", "email"], // fields available for search in filter } } ], options: { listPageSize: 12, allowedActions: { edit: true, delete: true, show: true, filter: true, }, }, } as AdminForthResourceInput; ``` -------------------------------- ### Run Prisma Migrations Source: https://adminforth.dev/docs/tutorial/Plugins/open-signup Executes the necessary commands to generate and apply database migrations after schema changes, including adding the email confirmation field. ```bash npm run makemigration -- --name add-email-confirmed-to-adminuser ; npm run migrate:local ``` -------------------------------- ### Get request header value (get) Source: https://adminforth.dev/docs/api/Back/interfaces/ITranslateExpressRequest The `get` method retrieves the value of a specified request header. It is case-insensitive for most headers, with 'Referrer' and 'Referer' being treated interchangeably. If the header is not found, it returns `undefined`. ```javascript const contentType = req.get('Content-Type'); console.log(contentType); // Example: "application/json" ``` -------------------------------- ### Install Twitch OAuth Adapter using npm Source: https://adminforth.dev/docs/tutorial/Plugins/oauth This command installs the necessary AdminForth Twitch OAuth adapter package from npm. Ensure you have Node.js and npm installed on your system. ```bash npm install @adminforth/twitch-oauth-adapter --save ``` -------------------------------- ### Install Foreign Inline List Plugin with npm Source: https://adminforth.dev/docs/tutorial/Plugins/ForeignInlineList This command installs the Foreign Inline List plugin using npm. Ensure you have Node.js and npm installed on your system. ```bash npm i @adminforth/foreign-inline-list --save ``` -------------------------------- ### Start HTTP Server Listening Source: https://adminforth.dev/docs/api/Back/interfaces/IExpressHttpServer The listen method starts the HTTP server, making it listen on a specified port. It can optionally take a host parameter. A callback function can be provided to execute code once the server starts listening. ```javascript // Listen on port 3000 server.listen(3000, () => { console.log('Server listening on port 3000'); }); // Listen on port 8080 on host 'localhost' server.listen(8080, 'localhost', () => { console.log('Server listening on port 8080'); }); ``` -------------------------------- ### Seed Database with Fake Apartments (TypeScript) Source: https://adminforth.dev/docs/tutorial/gettingStarted This TypeScript function seeds the 'aparts' resource in an AdminForth database with 100 fake apartment records. It checks if records already exist to prevent duplication. Each record includes randomly generated fields like title, square meter, price, number of rooms, description, creation date, listing status, and country. It utilizes the AdminForth SDK for database operations. ```typescript async function seedDatabase() { if (await admin.resource('aparts').count() > 0) { return } for (let i = 0; i < 100; i++) { await admin.resource('aparts').create({ id: `${i}`, title: `Apartment ${i}`, square_meter: (Math.random() * 100).toFixed(1), price: (Math.random() * 10000).toFixed(2), number_of_rooms: Math.floor(Math.random() * 4) + 1, description: 'Next gen apartments', created_at: (new Date(Date.now() - Math.random() * 60 * 60 * 24 * 14 * 1000)).toISOString(), listed: i % 2 == 0, country: `${['US', 'DE', 'FR', 'GB', 'NL', 'IT', 'ES', 'DK', 'PL', 'UA'][Math.floor(Math.random() * 10)]}` }); }; }; ``` -------------------------------- ### Install Many2Many Plugin with npm Source: https://adminforth.dev/docs/tutorial/Plugins/many2many Installs the Many2Many plugin using npm. This is the first step to integrating the plugin into your project. ```bash npm i @adminforth/many2many ```