### Install and Start Frontend Development Server Source: https://github.com/foalts/foal/blob/master/docs/docs/tutorials/real-world-example-with-react/7-add-frontend.md Navigate to the frontend directory, install dependencies, and start the development server. ```bash cd frontend-app npm install npm run start ``` -------------------------------- ### Basic API Controller with GET and POST methods Source: https://github.com/foalts/foal/blob/master/docs/docs/common/openapi-and-swagger-ui.md This example demonstrates a basic API controller with GET and POST methods for reading and creating products, along with OpenAPI information. ```APIDOC ## GET /products ### Description Reads a list of products. ### Method GET ### Endpoint /products ### Response #### Success Response (200) - description (string) - successful operation ### Response Example { "example": "successful operation" } ``` ```APIDOC ## POST /products ### Description Creates a new product. ### Method POST ### Endpoint /products ### Response #### Success Response (200) - description (string) - successful operation ### Response Example { "example": "successful operation" } ``` -------------------------------- ### Basic API Controller with GET and POST operations Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-3.x/common/openapi-and-swagger-ui.md This example demonstrates a basic API controller with GET and POST methods for reading and creating products. FoalTS automatically maps these methods to OpenAPI paths and operations. ```APIDOC ## GET /products ### Description Reads a list of products. ### Method GET ### Endpoint /products ### Response #### Success Response (200) - description (string) - successful operation ### Response Example { "example": "successful operation" } ## POST /products ### Description Creates a new product. ### Method POST ### Endpoint /products ### Response #### Success Response (200) - description (string) - successful operation ### Response Example { "example": "successful operation" } ``` -------------------------------- ### Start Production Server Source: https://github.com/foalts/foal/blob/master/docs/docs/cli/commands.md Starts the server using the pre-built application files. ```bash npm run start ``` -------------------------------- ### Paginated GET Request Example Source: https://github.com/foalts/foal/blob/master/docs/docs/common/rest-blueprints.md Demonstrates how to use `skip` and `take` query parameters for pagination in a GET request to a REST API collection. ```bash GET /products?skip=10&take=20 ``` -------------------------------- ### Start Development Server Source: https://github.com/foalts/foal/blob/master/docs/docs/tutorials/real-world-example-with-react/1-introduction.md Navigate into the backend application directory and start the development server. ```bash cd backend-app npm run dev ``` -------------------------------- ### Start scheduler with pm2 Source: https://github.com/foalts/foal/blob/master/docs/docs/common/async-tasks.md Use pm2 to run the scheduler in the background. Install the Foal CLI locally first. ```sh npm install @foal/cli ``` ```sh pm2 start ./node_modules/.bin/foal --name scheduler -- run schedule-jobs arg1=value1 ``` -------------------------------- ### Start Foal Development Server Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/tutorials/real-world-example-with-react/1-introduction.md Navigate into the backend application directory and start the development server. ```bash cd backend-app npm run develop ``` -------------------------------- ### Reading Products Endpoint Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/common/openapi-and-swagger-ui.md This example shows how to define a GET endpoint for reading products and associate it with a successful response. ```APIDOC ## GET /products ### Description Reads a list of products. ### Method GET ### Endpoint /products ### Response #### Success Response (200) - description (string) - successful operation ### Response Example { "example": "{\"description\": \"successful operation\"}" } ``` -------------------------------- ### Defining API Endpoints and Responses Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/api-section/openapi-and-swagger-ui.md This example shows how to define GET and POST endpoints for reading and creating products, including response schemas and descriptions. ```APIDOC ## GET /products ### Description Reads a list of products. ### Method GET ### Endpoint /products ### Response #### Success Response (200) - **description** (string) - successful operation **content** (object) - **application/json** (object) - **schema** (object) - **$ref** (string) - "#/components/schemas/product" ## POST /products ### Description Creates a new product. ### Method POST ### Endpoint /products ### Response #### Success Response (200) - **description** (string) - successful operation **content** (object) - **application/json** (object) - **schema** (object) - **$ref** (string) - "#/components/schemas/product" ``` -------------------------------- ### Install GraphiQL Package Source: https://github.com/foalts/foal/blob/master/docs/blog/2021-04-22-version-2.3-release-notes.md Install the GraphiQL package to enable GraphiQL page generation. ```bash npm install @foal/graphiql ``` -------------------------------- ### Install Prisma Dependencies Source: https://github.com/foalts/foal/blob/master/docs/docs/databases/other-orm/prisma.md Install the necessary Prisma dependencies for your project. ```bash npm install prisma --save-dev npm install @prisma/client ``` -------------------------------- ### Install Social Authentication Packages Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/tutorials/real-world-example-with-react/15-social-auth.md Install the necessary packages for social authentication and node-fetch. ```bash npm install @foal/social node-fetch@2 ``` -------------------------------- ### Install React Dependencies Source: https://github.com/foalts/foal/blob/master/docs/docs/frontend/server-side-rendering.md Install the necessary React and ReactDOM packages for server-side rendering. ```bash npm install react react-dom ``` -------------------------------- ### Install GraphQL Packages Source: https://github.com/foalts/foal/blob/master/docs/docs/common/graphql.md Install the necessary packages for GraphQL integration with FoalTS. ```bash npm install graphql@16 @foal/graphql ``` -------------------------------- ### Install Nuxt Dependency Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/frontend/nuxt.js.md Navigate to your server directory and install the Nuxt package using npm. ```bash npm install nuxt ``` -------------------------------- ### Install Build Dependency Source: https://github.com/foalts/foal/blob/master/docs/docs/common/graphql.md Install `cpx2` to copy GraphQL schema files during the build process. ```bash npm install cpx2 --save-dev ``` -------------------------------- ### Install gRPC Dependencies Source: https://github.com/foalts/foal/blob/master/docs/docs/common/gRPC.md Install the necessary gRPC libraries for Node.js and a development dependency for file copying. ```bash npm install @grpc/grpc-js @grpc/proto-loader npm install cpx2 --save-dev ``` -------------------------------- ### Define a Controller with a GET Endpoint Source: https://github.com/foalts/foal/blob/master/docs/docs/architecture/controllers.md This example shows a controller class with a GET endpoint that requires JWT authentication and returns the current user. ```typescript import { Context, Get, HttpResponseOK } from '@foal/core'; import { JWTRequired } from '@foal/jwt'; class ApiController { @Get('/users/me') @JWTRequired() getCurrentUser(ctx: Context) { return new HttpResponseOK(ctx.user); } } ``` -------------------------------- ### Configuration with Reserved and Custom Parameters Source: https://github.com/foalts/foal/blob/master/docs/docs/architecture/configuration.md Illustrates how to structure configuration files, including reserved 'settings' parameters and custom parameters. ```json { "settings": { "session": { "store": "@foal/typeorm" } }, "customConfiguration": { "message": "hello world" } } ``` -------------------------------- ### JS Configuration File Example Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/upgrade-to-v2/config-system.md Configuration files can now be written in JavaScript, allowing for dynamic configuration values using `Env.get`. ```javascript const { Env } = require('@foal/core'); module.exports = { settings: { debug: false, jwt: { secret: Env.get('SETTINGS_JWT_SECRET') } } } ``` -------------------------------- ### Configuration with Custom Parameters (YAML) Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/architecture/configuration.md Example of a configuration file in YAML format, including reserved 'settings' and custom parameters. ```yaml settings: session: store: "@foal/typeorm" customConfiguration: message: hello world ``` -------------------------------- ### Read Cookies Source: https://github.com/foalts/foal/blob/master/docs/docs/architecture/controllers.md Access cookies sent with the request via the `ctx.request.cookies` object. For example, to get a `sessionID` cookie. ```typescript import { Context, HttpResponseOK, Get } from '@foal/core'; class AppController { @Get('/') index(ctx: Context) { const sessionID: string|undefined = ctx.request.cookies.sessionID; // Do something. return new HttpResponseOK(); } } ``` -------------------------------- ### Basic App Controller Setup Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/common/graphql.md Set up the main application controller to route GraphQL requests to the API controller. ```typescript export class AppController { subControllers = [ controller('/graphql', ApiController) ] } ``` -------------------------------- ### TypeORM Test Setup with FoalTS Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-3.x/databases/typeorm/introduction.md Example of setting up and tearing down a TypeORM DataSource for testing within a FoalTS application. ```typescript import { DataSource } from 'typeorm'; import { createDataSource } from '../db'; describe('xxx', () => { let dataSource: DataSource; beforeEach(async () => { dataSource = createDataSource(); await dataSource.initialize(); }); afterEach(async () => { if (dataSource) { await dataSource.destroy() } }); it('yyy', () => { // ... }); }); ``` -------------------------------- ### Files to Upload (Install & Build on Local Host) Source: https://github.com/foalts/foal/blob/master/docs/docs/deployment-and-environments/checklist.md List of files and directories to upload if dependencies are installed and the app is built on the local host. ```sh build/ config/ node_modules/ package-lock.json package.json public/ # this may depend on how the platform manages static files ``` -------------------------------- ### Basic Server GET Request Test Source: https://github.com/foalts/foal/blob/master/docs/docs/testing/e2e-testing.md A simple E2E test using SuperTest to verify that the server returns a 200 status code on GET requests to the root path. Requires application setup and database initialization. ```typescript // 3p import { createApp } from '@foal/core'; import * as request from 'supertest'; import { DataSource } from 'typeorm'; // App import { AppController } from '../app/app.controller'; import { createDataSource } from '../db'; describe('The server', () => { let app; let dataSource: DataSource; before(async () => { app = await createApp(AppController); dataSource = createDataSource(); await dataSource.initialize(); }); after(async () => { if (dataSource) { await dataSource.destroy(); } }); it('should return a 200 status on GET / requests.', () => { return request(app) .get('/') .expect(200); }); }); ``` -------------------------------- ### Configuration with Custom Parameters (JS) Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/architecture/configuration.md Example of a configuration file in JavaScript format, including reserved 'settings' and custom parameters. ```javascript module.exports = { settings: { session: { store: "@foal/typeorm" } }, customConfiguration: { message: "hello world" } } ``` -------------------------------- ### Simple SuperTest E2E Test Example Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/testing/e2e-testing.md A basic example demonstrating how to use SuperTest to make a GET request to the root path and assert a 200 status code. Requires FoalTS app creation and TypeORM connection management. ```typescript // 3p import { createApp } from '@foal/core'; import * as request from 'supertest'; import { getConnection } from 'typeorm'; // App import { AppController } from '../app/app.controller'; describe('The server', () => { let app; before(async () => { app = await createApp(AppController); }); after(() => getConnection().close()); it('should return a 200 status on GET / requests.', () => { return request(app) .get('/') .expect(200); }); }); ``` -------------------------------- ### Initialize Prisma Project Source: https://github.com/foalts/foal/blob/master/docs/docs/databases/other-orm/prisma.md Initialize a new Prisma project. This command creates the initial Prisma configuration files. ```bash npx prisma init ``` -------------------------------- ### Read Request Headers Source: https://github.com/foalts/foal/blob/master/docs/docs/architecture/controllers.md Retrieve specific request headers using the `ctx.request.get()` method. For example, to get the `Authorization` header. ```typescript import { Context, HttpResponseOK, Get } from '@foal/core'; class AppController { @Get('/') index(ctx: Context) { const token = ctx.request.get('Authorization'); // Do something. return new HttpResponseOK(); } } ``` -------------------------------- ### Read Path Parameters Source: https://github.com/foalts/foal/blob/master/docs/docs/architecture/controllers.md Retrieve path parameters from the request using `ctx.request.params`. For example, to get an ID from a URL like `/products/3`. ```typescript import { Context, HttpResponseOK, Get } from '@foal/core'; class AppController { @Get('/products/:id') readProduct(ctx: Context) { const productId = ctx.request.params.id; // Do something. return new HttpResponseOK(); } } ``` -------------------------------- ### Build Application, Scripts, and Migrations (v2 vs v1) Source: https://github.com/foalts/foal/blob/master/docs/blog/2021-02-17-whats-new-in-version-2-part-1.md Compares the single build command in v2 to the multiple commands in v1 for building the application, scripts, and migrations. Unit and e2e tests are not included. ```bash npm run build ``` ```bash npm run build:app npm run build:scripts npm run build:migrations ``` -------------------------------- ### Basic GraphQL Controller Setup Source: https://github.com/foalts/foal/blob/master/docs/docs/common/graphql.md Set up a basic GraphQL controller in FoalTS using a schema and resolvers. ```typescript import { GraphQLController } from '@foal/graphql'; import { buildSchema } from 'graphql'; const schema = buildSchema(` type Query { hello: String } `); const root = { hello: () => { return 'Hello world!'; }, }; export class ApiController extends GraphQLController { schema = schema; resolvers = root; } ``` -------------------------------- ### Accessing ServiceManager in a Controller Source: https://github.com/foalts/foal/blob/master/docs/docs/architecture/services-and-dependency-injection.md Demonstrates how to inject and use the ServiceManager to get a service instance within a FoalTS controller. Ensure '@foal/core' is installed. ```typescript import { dependency, Get, HttpResponseOK, ServiceManager } from '@foal/core'; class MyService { foo() { return 'foo'; } } class MyController { @dependency services: ServiceManager; @Get('/bar') bar() { const msg = this.services.get(MyService).foo(); return new HttpResponseOK(msg); } } ``` -------------------------------- ### Reading Specific Product Endpoint Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/common/openapi-and-swagger-ui.md This example defines a GET endpoint to read a specific product by its ID, referencing a reusable schema component. ```APIDOC ## GET /products/:productId ### Description Reads a specific product by its ID. ### Method GET ### Endpoint /products/:productId ### Parameters #### Path Parameters - **productId** (string) - Required - The ID of the product to retrieve. ### Response #### Success Response (200) - description (string) - successful operation ### Response Example { "example": "{\"description\": \"successful operation\"}" } ``` -------------------------------- ### Compare Migration Commands: v1 vs v2 Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/upgrade-to-v2/cli-commands.md This example shows the evolution of migration commands from Foal v1 to v2. Version 2 simplifies the process, requiring fewer commands and abstracting away build steps. ```bash # Version 1 npm run build:app npm run migration:generate -- -n my_migration npm run build:migrations npm run migration:run # Version 2 npm run makemigrations npm run migrations ``` -------------------------------- ### Install and Configure File Copying for Build Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-3.x/common/graphql.md Install `cpx2` for development and update `package.json` scripts to copy GraphQL files during the build and development processes. ```bash npm install cpx2 --save-dev ``` ```json { "scripts": { "build": "foal rmdir build && cpx \"src/**/*.graphql\" build && tsc -p tsconfig.app.json", "dev": "npm run build && concurrently \"cpx \\\"src/**/*.graphql\\\" build -w\" \"tsc -p tsconfig.app.json -w\" \"supervisor -w ./build,./config -e js,json,yml,graphql --no-restart-on error ./build/index.js\"", "build:test": "foal rmdir build && cpx \"src/**/*.graphql\" build && tsc -p tsconfig.test.json", "test": "npm run build:test && concurrently \"cpx \\\"src/**/*.graphql\\\" build -w\" \"tsc -p tsconfig.test.json -w\" \"mocha --file ./build/test.js -w --watch-files build \"./build/**/*.spec.js\"\"", "build:e2e": "foal rmdir build && cpx \"src/**/*.graphql\" build && tsc -p tsconfig.e2e.json", "e2e": "npm run build:e2e && concurrently \"cpx \\\"src/**/*.graphql\\\" build -w\" \"tsc -p tsconfig.e2e.json -w\" \"mocha --file ./build/e2e.js -w --watch-files build \"./build/e2e/**/*.js\"\"", ... } } ``` -------------------------------- ### Read Query Parameters Source: https://github.com/foalts/foal/blob/master/docs/docs/architecture/controllers.md Access query parameters from the request URL using `ctx.request.query`. For example, to get a `limit` value from `/products?limit=3`. ```typescript import { Context, HttpResponseOK, Get } from '@foal/core'; class AppController { @Get('/products') readProducts(ctx: Context) { const limit = ctx.request.query.limit; // Do something. return new HttpResponseOK(); } } ``` -------------------------------- ### App Controller Setup Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/authentication-and-access-control/quick-start.md Defines the main application controller, including sub-controllers for authentication and API, and initializes the database connection. ```typescript import { controller, IAppController } from '@foal/core'; import { createConnection } from 'typeorm'; import { ApiController, AuthController } from './controllers'; export class AppController implements IAppController { subControllers = [ controller('/auth', AuthController), controller('/api', ApiController), ]; async init() { await createConnection(); } } ``` -------------------------------- ### Create Project Directory Source: https://github.com/foalts/foal/blob/master/docs/docs/tutorials/real-world-example-with-react/1-introduction.md Create a new directory for your project. ```bash mkdir foal-react-tuto ``` -------------------------------- ### Test Suite with TypeORM DataSource Initialization Source: https://github.com/foalts/foal/blob/master/docs/docs/databases/typeorm/introduction.md Example test setup using TypeORM's DataSource for initializing and destroying the database connection before and after each test. ```typescript import { DataSource } from 'typeorm'; import { createDataSource } from '../db'; describe('xxx', () => { let dataSource: DataSource; beforeEach(async () => { dataSource = createDataSource(); await dataSource.initialize(); }); afterEach(async () => { if (dataSource) { await dataSource.destroy() } }); it('yyy', () => { // ... }); }); ``` -------------------------------- ### Documenting Controller Methods Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-4.x/common/openapi-and-swagger-ui.md Use the @ApiOperation decorator on controller methods to describe their functionality, including request methods, paths, and responses. This example shows how to document a GET request to '/products'. ```APIDOC ## OpenAPI ### The Basics Then each controller method can be documented with the `@ApiOperation` decorator. ```typescript import { ApiOperation, Get } from '@foal/core'; // ... export class ApiController { @Get('/products') @ApiOperation({ responses: { 200: { content: { 'application/json': { schema: { items: { properties: { name: { type: 'string' } }, type: 'object', required: [ 'name' ] }, type: 'array', } } }, description: 'successful operation' } }, summary: 'Return a list of all the products.' }) readProducts() { // ... } } ``` ``` -------------------------------- ### Create gRPC Server Service Source: https://github.com/foalts/foal/blob/master/docs/docs/common/gRPC.md Sets up and starts a gRPC server, loading the proto definition and adding the Greeter service. Requires @grpc/grpc-js and @grpc/proto-loader. ```typescript // std import { join } from 'path'; // 3p import { dependency } from '@foal/core'; import * as grpc from '@grpc/grpc-js'; import * as protoLoader from '@grpc/proto-loader'; // App import { Greeter } from './greeter.service'; export class Grpc { @dependency greeter: Greeter; boot(): Promise { const PROTO_PATH = join(__dirname, '../spec.proto'); const packageDefinition = protoLoader.loadSync( PROTO_PATH, { keepCase: true, longs: String, enums: String, defaults: true, oneofs: true } ); const helloProto: any = grpc.loadPackageDefinition(packageDefinition).helloworld; const server = new grpc.Server(); server.addService(helloProto.Greeter.service, this.greeter as any); // OR // server.addService(helloProto.Greeter.service, { // sayHello: this.greeter.sayHello.bind(this.greeter) // } as any); return new Promise((resolve, reject) => { server.bindAsync('0.0.0.0:50051', grpc.ServerCredentials.createInsecure(), error => { if (error) { return reject(error); } server.start(); return resolve(); }); }) } } ``` -------------------------------- ### Product Controller with OpenAPI Schema Validation Source: https://github.com/foalts/foal/blob/master/docs/blog/2021-03-02-whats-new-in-version-2-part-2.md This example demonstrates how to define an OpenAPI schema for a 'Product' and use it to validate both the request body for POST requests and path parameters for GET requests. ```APIDOC ## POST / ### Description Creates a new product in the database. ### Method POST ### Endpoint / ### Parameters #### Request Body - **(object)** - Required - The product data to create. - **id** (number) - Required - The product ID. - **name** (string) - Required - The product name. ### Request Example ```json { "id": 1, "name": "Example Product" } ``` ### Response #### Success Response (200) - **(object)** - The identifier of the newly created product. - **id** (number) - The ID of the created product. #### Response Example ```json { "id": 1 } ``` ## GET /:productId ### Description Retrieves a specific product by its ID. ### Method GET ### Endpoint /:productId ### Parameters #### Path Parameters - **productId** (number) - Required - The ID of the product to retrieve. ### Response #### Success Response (200) - **(object)** - The product found in the database. - **id** (number) - The product ID. - **name** (string) - The product name. #### Response Example ```json { "id": 1, "name": "Example Product" } ``` #### Error Response (404) - Product not found. ``` -------------------------------- ### Install MySQL or PostgreSQL Driver Source: https://github.com/foalts/foal/blob/master/docs/docs/tutorials/real-world-example-with-react/2-database-set-up.md Install the appropriate database driver using npm. Use `mysql` for MySQL or `pg` for PostgreSQL. ```bash npm install mysql # or pg ``` -------------------------------- ### FoalTS Application Structure with Sub-Controllers and Hooks Source: https://github.com/foalts/foal/blob/master/docs/docs/architecture/architecture-overview.md An example of a more complex FoalTS application. It includes a root controller with a hook, a GET route, and a sub-controller mounted at '/api' which itself has routes for listing and retrieving products. ```typescript import { Context, controller, Get, Hook, HttpResponseNotFound, HttpResponseOK } from '@foal/core'; import { JWTRequired } from '@foal/jwt'; @JWTRequired() class ApiController { private products = [ { id: 1, name: 'phone' }, { id: 2, name: 'computer' }, ] @Get('/products') listProducts() { return new HttpResponseOK(this.products); } @Get('/products/:id') getProduct(ctx: Context) { const product = this.products.find( p => p.id === parseInt(ctx.request.params.id, 10) ); if (!product) { return new HttpResponseNotFound(); } return new HttpResponseOK(product); } } @Hook(() => { console.log('Receiving a request...') }) class AppController { subControllers = [ controller('/api', ApiController) ]; @Get('/') index() { return new HttpResponseOK('Welcome!'); } } ``` -------------------------------- ### Files to Upload (Install & Build on Remote Host) Source: https://github.com/foalts/foal/blob/master/docs/docs/deployment-and-environments/checklist.md List of files and directories to upload if dependencies are installed and the app is built on the remote host. ```sh config/ package-lock.json package.json public/ # this may depend on how the platform manages static files src/ tsconfig.app.json ``` -------------------------------- ### Basic Rate Limiting Setup Source: https://github.com/foalts/foal/blob/master/docs/docs/security/rate-limiting.md Configure express-rate-limit to limit requests per IP address. This example sets a limit of 100 requests per 15 minutes and customizes the response headers for limited requests. ```typescript import { Config, createApp, Logger, ServiceManager } from '@foal/core'; import * as express from 'express'; import { rateLimit } from 'express-rate-limit'; // App import { AppController } from './app/app.controller'; async function main() { const expressApp = express(); expressApp.use(rateLimit({ // Limit each IP to 100 requests per windowMs max: 100, // 15 minutes windowMs: 15 * 60 * 1000, handler (req, res, next) { // Set default FoalTS headers to the response of limited requests res.removeHeader('X-Powered-By'); res.setHeader('X-Content-Type-Options', 'nosniff'); res.setHeader('X-Frame-Options', 'SAMEORIGIN'); res.setHeader('Strict-Transport-Security', 'max-age=31536000; includeSubDomains'); // Send the response with the default statusCode and message from rateLimit res.status(this.statusCode || 429).send(this.message); } })); const serviceManager = new ServiceManager(); const logger = serviceManager.get(Logger); const app = await createApp(AppController, { expressInstance: expressApp }); const port = Config.get('port', 'number', 3001); app.listen(port, () => logger.info(`Listening on port ${port}...`)); } main() .catch(err => { console.error(err); process.exit(1); }); ``` -------------------------------- ### Database Credentials in JSON Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/databases/typeorm.md Example of how to provide database credentials in a JSON configuration file. ```json { // ... "database": { "host": "localhost", "port": 3306, "username": "root", "password": "password", "database": "my-db" } } ``` -------------------------------- ### Define and Use OpenAPI Schema for Product Validation Source: https://github.com/foalts/foal/blob/master/docs/blog/2021-03-02-whats-new-in-version-2-part-2.md Define an OpenAPI schema for 'Product' and use it to validate both the request body in a POST request and a path parameter in a GET request. This example also shows how to document the response schema. ```typescript import { ApiDefineSchema, ApiResponse, Context, Get, HttpResponseNotFound, HttpResponseOK, Post, ValidateBody, ValidatePathParam } from '@foal/core'; import { Product } from '../../entities'; // First we define the OpenAPI schema "Product". @ApiDefineSchema('Product', { type: 'object', properties: { id: { type: 'number' }, name: { type: 'string' } }, additionalProperties: false, required: ['id', 'name'], }) export class ProductController { @Post('/') // We use the schema "Product" here to validate the request body. @ValidateBody({ $ref: '#/components/schemas/Product' }) async createProduct(ctx: Context) { const result = await Product.insert(ctx.request.body); return new HttpResponseOK(result.identifiers[0]); } @Get('/:productId') // We use the schema "Product" here to validate the URL parameter. @ValidatePathParam('productId', { $ref: '#/components/schemas/Product/properties/id' }) // We give some extra information on the format of the response. @ApiResponse(200, { description: 'Product found in the database', content: { 'application/json': { schema: { $ref: '#/components/schemas/Product' } } } }) async readProduct(ctx: Context, { productId }) { const product = await Product.findOne({ id: productId }); if (!product) { return new HttpResponseNotFound(); } return new HttpResponseOK(product); } } ``` -------------------------------- ### Basic API Controller with OpenAPI Decorators Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/common/openapi-and-swagger-ui.md Illustrates a basic API controller using FoalTS decorators to define OpenAPI information for GET and POST methods. This setup automatically resolves path items and operations for the OpenAPI specification. ```typescript import { ApiResponse, Get, Post } from '@foal/core'; @ApiInfo({ title: 'A Great API', version: '1.0.0' }) export class ApiController { @Get('/products') @ApiResponse(200, { description: 'successful operation' }) readProducts() { // ... } @Post('/products') @ApiResponse(200, { description: 'successful operation' }) createProduct() { // ... } } ``` ```yaml openapi: 3.0.0 info: title: 'A Great API' version: 1.0.0 paths: /products: # Foal automatically puts the "get" and "post" operations under the same path item as required by OpenAPI rules. get: responses: 200: description: successful operation post: responses: 200: description: successful operation ``` -------------------------------- ### Creating Product Endpoint Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/common/openapi-and-swagger-ui.md This example demonstrates a POST endpoint for creating products, including response details. ```APIDOC ## POST /products ### Description Creates a new product. ### Method POST ### Endpoint /products ### Response #### Success Response (200) - description (string) - successful operation ### Response Example { "example": "{\"description\": \"successful operation\"}" } ``` -------------------------------- ### Build and Run the Shell Script Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/tutorials/simple-todo-list/4-the-shell-script-create-todo.md Build the application and then execute the create-todo script to add tasks to the database. ```bash npm run build ``` ```bash foal run create-todo text="Read the docs" foal run create-todo text="Create my first application" foal run create-todo text="Write tests" ``` -------------------------------- ### Handle GET Requests for 404 Source: https://github.com/foalts/foal/blob/master/docs/docs/frontend/not-found-page.md Use the @Get('*') decorator to catch all GET requests that do not match any other defined routes and return a 404 response. ```typescript import { Get, HttpResponseNotFound, HttpResponseOK } from '@foal/core'; class ViewController { @Get('/home') home() { return new HttpResponseOK('You are on the home page!'); } } class AppController { subControllers = [ ViewController ]; @Get('*') notFound() { return new HttpResponseNotFound('The page you are looking for does not exist.'); } } ``` -------------------------------- ### Install Windows Build Tools Source: https://github.com/foalts/foal/blob/master/docs/docs/tutorials/simple-todo-list/installation-troubleshooting.md Run this command from an elevated PowerShell or CMD.exe to install necessary dependencies for node-gyp on Windows. ```bash npm install --global windows-build-tools ``` -------------------------------- ### Install express-rate-limit Source: https://github.com/foalts/foal/blob/master/docs/docs/security/rate-limiting.md Install the express-rate-limit package using npm. ```bash npm install express-rate-limit ``` -------------------------------- ### Database Credentials in YAML Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/databases/typeorm.md Example of how to provide database credentials in a YAML configuration file. ```yaml # ... database: host: localhost port: 3306 username: root password: password database: my-db ``` -------------------------------- ### Install class-transformer Source: https://github.com/foalts/foal/blob/master/docs/docs/common/serialization.md Install the class-transformer library using npm. ```bash npm install class-transformer ``` -------------------------------- ### Install Redis Store Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/authentication/session-tokens.md Install the Redis store package for FoalTS. ```bash npm install @foal/redis ``` -------------------------------- ### Install Swagger Package Source: https://github.com/foalts/foal/blob/master/docs/docs/tutorials/real-world-example-with-react/6-swagger-interface.md Install the @foal/swagger package using npm. ```bash npm install @foal/swagger ``` -------------------------------- ### Run Development Server Source: https://github.com/foalts/foal/blob/master/docs/docs/cli/commands.md Builds the source code and starts the server with hot-reloading. This is the primary command for development. ```bash npm run dev ``` -------------------------------- ### Configuration with Reserved and Custom Parameters Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/architecture/configuration.md Demonstrates how to define both framework-reserved settings (like session store) and custom configuration parameters within YAML, JSON, or JavaScript files. ```yaml settings: session: store: "@foal/typeorm" customConfiguration: message: hello world ``` ```json { "settings": { "session": { "store": "@foal/typeorm" } }, "customConfiguration": { "message": "hello world" } } ``` ```javascript module.exports = { settings: { session: { store: "@foal/typeorm" } }, customConfiguration: { message: "hello world" } } ``` -------------------------------- ### Basic Swagger UI Setup Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/api-section/openapi-and-swagger-ui.md Configure your AppController to serve the Swagger UI at the /swagger path. ```typescript import { ApiController, OpenApiController } from './controllers'; export class AppController { subControllers = [ controller('/api', ApiController), controller('/swagger', OpenApiController) ] } ``` ```typescript import { SwaggerController } from '@foal/swagger'; import { ApiController } from './api.controller'; export class OpenApiController extends SwaggerController { options = { controllerClass: ApiController }; } ``` -------------------------------- ### Install PostgreSQL Driver Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/version-2.x/databases/typeorm.md Install the necessary npm package for PostgreSQL support. ```sh npm install pg --save ``` -------------------------------- ### Create New FoalTS Backend and Vue Frontend Source: https://github.com/foalts/foal/blob/master/docs/docs/frontend/angular-react-vue.md This sequence of commands sets up a new project with a FoalTS backend and a Vue frontend, then connects them. ```bash mkdir my-app cd my-app npx @foal/cli createapp backend vue create frontend cd backend npx foal connect vue ../frontend ``` -------------------------------- ### Install TypeORM Store Source: https://github.com/foalts/foal/blob/master/docs/i18n/id/docusaurus-plugin-content-docs/current/authentication/session-tokens.md Install the TypeORM store package and its peer dependency. ```bash npm install typeorm@0.3.17 @foal/typeorm ``` -------------------------------- ### PostgreSQL Database Configuration Source: https://github.com/foalts/foal/blob/master/docs/docs/databases/typeorm/introduction.md Example configuration for connecting to a PostgreSQL database in default.json. ```json { // ... "database": { "type": "postgres", "host": "localhost", "port": 5432, "username": "root", "password": "password", "database": "my-db" } } ```