From 63d3290b112ae5dcab86b910ad46a5f80ae0d362 Mon Sep 17 00:00:00 2001 From: Derick Sozo Date: Tue, 10 Sep 2024 14:02:37 +0700 Subject: [PATCH 01/12] (docs): Adding a new guide around adding custom code / business logic to your service after building it. It clarifies the process of merging branches, modifying files, and more. --- docs/getting-started/add-custom-code.md | 236 ++++++++++++++++++++++++ sidebars.js | 7 +- 2 files changed, 240 insertions(+), 3 deletions(-) create mode 100644 docs/getting-started/add-custom-code.md diff --git a/docs/getting-started/add-custom-code.md b/docs/getting-started/add-custom-code.md new file mode 100644 index 00000000..189312bf --- /dev/null +++ b/docs/getting-started/add-custom-code.md @@ -0,0 +1,236 @@ +--- +id: add-custom-code +title: How To Add Custom Code To Your Service +sidebar_label: Add Custom Code To Your Service +slug: /how-to/add-custom-code-to-your-service +--- + +# How To Add Custom Code To Your Service + +While Amplication generates a robust, production-ready backend for your application, you'll often need to add custom business logic or additional functionality. This guide will walk you through the process of adding custom code to your Amplication-generated service while maintaining compatibility with future builds. + +## Prerequisites + +Before you begin, make sure you have: + +1. [Created your first service](/first-service/) +2. [Set up entities](/set-up-entities/) for your service +3. [Configured roles and permissions](/configure-roles-and-permissions/) +4. [Added plugins to your service](/add-plugins-service/) +5. [Committed changes and built a new version](/commit-and-build-new-versions/) + +## Understanding Custom Code in Amplication + +When adding custom code to your Amplication-generated service, it's important to understand how Amplication manages and preserves your changes: + +1. Custom code is added to specific files that Amplication recognizes and preserves during rebuilds. +2. You'll work directly in your git repository, making changes to the generated code. +3. Amplication uses a folder structure that separates customizable and non-customizable code. +4. The `base` folder contains files that should not be modified, as they will be overwritten by Amplication. +5. Files outside the `base` folder can be safely customized and will be preserved across builds. + +Let's walk through the process of adding custom code to implement a password reset feature for the User entity. + +## Step 1: Merge the Amplication Branch + +First, ensure that your local repository is up-to-date with the latest Amplication-generated code: + +1. Open your terminal and navigate to your project's root directory. +2. Switch to your main branch: + ```bash + git checkout main + ``` +3. Pull the latest changes: + ```bash + git pull origin main + ``` +4. Merge the `amplication` branch into your main branch: + ```bash + git merge amplication + ``` +5. Push the merged changes to your remote repository: + ```bash + git push origin main + ``` + +## Step 2: Create a New Branch for Custom Code + +Create a new branch from the main branch to make your custom code changes: + +```bash +git checkout -b feature/password-reset main +``` + +## Step 3: Locate the Correct Files + +Navigate to your service's `src` folder. You'll find a folder for each entity. In this case, we'll be working with the `user` folder: + +``` +src +└── user + ├── base + │ ├── user.controller.base.ts + │ ├── user.service.base.ts + │ └── ... + ├── user.controller.ts + ├── user.module.ts + ├── user.resolver.ts + └── user.service.ts +``` + +We'll be modifying `user.service.ts` and `user.controller.ts` to add our custom password reset functionality. + +## Step 4: Add Custom Logic to the Service + +Open `src/user/user.service.ts`. This file extends the base service and is where we'll add our custom method. + +1. Add the necessary imports at the top of the file: + +```typescript +import { Injectable } from "@nestjs/common"; +import { PrismaService } from "nestjs-prisma"; +import { UserServiceBase } from "./base/user.service.base"; +import { PasswordService } from "../auth/password.service"; +import { User } from "./base/User"; +import { UserWhereUniqueInput } from "./base/UserWhereUniqueInput"; +``` + +2. Add the custom `resetPassword` method to the `UserService` class: + +```typescript +@Injectable() +export class UserService extends UserServiceBase { + constructor( + protected readonly prisma: PrismaService, + protected readonly passwordService: PasswordService + ) { + super(prisma, passwordService); + } + + async resetPassword(args: UserWhereUniqueInput): Promise { + const newPassword = Math.random().toString(36).slice(-8); // Generate a random password + const hashedPassword = await this.passwordService.hashPassword(newPassword); + + const updatedUser = await this.prisma.user.update({ + where: args, + data: { + password: hashedPassword + } + }); + + // In a real-world scenario, you'd want to send this password to the user securely + console.log(`New password for user ${updatedUser.id}: ${newPassword}`); + + return updatedUser; + } +} +``` + +## Step 5: Add a New Endpoint to the Controller + +Now, let's add a new endpoint to the User controller to expose our password reset functionality. Open `src/user/user.controller.ts`: + +1. Add the necessary imports at the top of the file: + +```typescript +import * as common from "@nestjs/common"; +import * as swagger from "@nestjs/swagger"; +import * as nestAccessControl from "nest-access-control"; +import { UserService } from "./user.service"; +import { UserControllerBase } from "./base/user.controller.base"; +import { User } from "./base/User"; +import { UserWhereUniqueInput } from "./base/UserWhereUniqueInput"; +import { AclValidateRequestInterceptor } from "../interceptors/aclValidateRequest.interceptor"; +``` + +2. Add the new `resetPassword` endpoint to the `UserController` class: + +```typescript +@swagger.ApiTags("users") +@common.Controller("users") +export class UserController extends UserControllerBase { + constructor( + protected readonly service: UserService, + @nestAccessControl.InjectRolesBuilder() + protected readonly rolesBuilder: nestAccessControl.RolesBuilder + ) { + super(service, rolesBuilder); + } + + @common.UseInterceptors(AclValidateRequestInterceptor) + @common.Patch("/:id/reset-password") + @nestAccessControl.UseRoles({ + resource: "User", + action: "update", + possession: "own", + }) + @swagger.ApiOkResponse({ type: User }) + @swagger.ApiNotFoundResponse({ type: errors.NotFoundException }) + @swagger.ApiForbiddenResponse({ type: errors.ForbiddenException }) + async resetPassword( + @common.Param() params: UserWhereUniqueInput + ): Promise { + return this.service.resetPassword(params); + } +} +``` + +## Step 6: Commit and Push Your Changes + +After adding your custom code, commit the changes to your git repository: + +```bash +git add . +git commit -m "Added custom password reset functionality" +git push origin feature/password-reset +``` + +## Step 7: Create a Pull Request + +Go to your repository on GitHub (or your chosen git provider) and create a new pull request: + +1. Set the base branch to `main` +2. Set the compare branch to `feature/password-reset` +3. Give your pull request a descriptive title and description +4. Create the pull request + +## Step 8: Merge the Pull Request + +After reviewing your changes, merge the pull request into the main branch. This step integrates your custom code with the main codebase. + +## Step 9: Rebuild Your Service in Amplication + +Now that you've added custom code to your repository and merged it into the main branch, you need to rebuild your service in Amplication to ensure everything works together: + +1. Go to your service in the Amplication web interface. +2. Click on "Commit Changes & Build" in the right sidebar. +3. In the commit message, write "Integrated custom password reset functionality". +4. Click "Commit Changes & Build" to start the build process. + +Amplication will now rebuild your service, integrating your custom code with the generated code. + +## You're Done! + +Congratulations! You've successfully added custom code to implement a password reset feature in your Amplication-generated service. This custom logic will now be available through your API, allowing users to reset their passwords. + +## Best Practices for Custom Code + +When adding custom code to your Amplication service, keep these best practices in mind: + +1. Always add custom code to the non-base files (e.g., `user.service.ts` instead of `user.service.base.ts`). +2. Use the types and interfaces generated by Amplication to ensure type safety. +3. Leverage the existing services and utilities provided by Amplication (like `PasswordService` in this example). +4. Document your custom code to make it easier for team members to understand and maintain. +5. Always create a new branch for your custom code changes. +6. Regularly merge the `amplication` branch into your main branch to stay up-to-date with Amplication-generated changes. + +## Next Steps + +Now that you know how to add custom code to your Amplication service, you can extend its functionality in various ways: + +- Implement complex business logic specific to your application +- Add custom API endpoints for specialized operations +- Integrate with external services or APIs +- Implement advanced validation and data processing + +Amplication is designed to be flexible, allowing you to leverage its powerful code generation while still giving you the freedom to customize your service as needed. diff --git a/sidebars.js b/sidebars.js index 5ec57a41..5070efe5 100644 --- a/sidebars.js +++ b/sidebars.js @@ -13,7 +13,8 @@ const sidebars = { "getting-started/set-up-entities", "getting-started/configure-roles-and-permissions", "getting-started/add-plugins-for-service", - "getting-started/commit-changes-and-build-new-versions" + "getting-started/commit-changes-and-build-new-versions", + "getting-started/add-custom-code" ], }, { @@ -25,9 +26,9 @@ const sidebars = { }, items: [ "getting-started/generated-app", - "getting-started/service-building-new-versions", + // "getting-started/service-building-new-versions", "getting-started/view-generated-code", - "how-to/add-custom-code", + // "how-to/add-custom-code", "getting-started/authentication", "concepts/event-driven-architecture", { From f766d8b1d0e73a41264a6829822964b11a0346b8 Mon Sep 17 00:00:00 2001 From: Derick Sozo Date: Tue, 10 Sep 2024 17:35:06 +0700 Subject: [PATCH 02/12] (docs): Updating the previous Custom Code page into a newer and more clear Understanding Code Code page that explains the philosophy and goes into the modifications that might happen to non-base files. --- docs/getting-started/view-generated-code.md | 4 +- docs/how-to/add-custom-code.md | 105 ++++++++------------ sidebars.js | 1 + 3 files changed, 47 insertions(+), 63 deletions(-) diff --git a/docs/getting-started/view-generated-code.md b/docs/getting-started/view-generated-code.md index a5db01ba..8e9cd7ee 100644 --- a/docs/getting-started/view-generated-code.md +++ b/docs/getting-started/view-generated-code.md @@ -1,11 +1,11 @@ --- id: view-generated-code title: Viewing the generated code -sidebar_label: View the generated code +sidebar_label: Code View Explained slug: /getting-started/view-generated-code --- -# Viewing the Generated Code +# Code View Explained Use **Code View** to view and explore the generated code. You can see the updated code before it is synced with GitHub or downloaded. diff --git a/docs/how-to/add-custom-code.md b/docs/how-to/add-custom-code.md index e4d02d3b..4f200197 100644 --- a/docs/how-to/add-custom-code.md +++ b/docs/how-to/add-custom-code.md @@ -1,95 +1,78 @@ --- -id: add-custom-code -title: How to add custom code to your services -sidebar_label: Add custom code to your services -slug: /how-to/custom-code +id: custom-code-overview +title: Understanding Custom Code in Amplication +sidebar_label: Understanding Custom Code +slug: /custom-code-overview +pagination_next: getting-started/add-custom-code --- -# Add custom code to your services +# Understanding Custom Code in Amplication -Although your application built with Amplication is fully functional and you can start using it as it was shipped, you probably want to add your core business logic and other functionality to your server. +This page provides an overview of how custom code works in Amplication and our vision for seamless integration between generated and custom code. ## The Vision -Our vision is that you will be able to add custom code to the server while keeping the ability to work on Amplication to update your data model, change permissions, add roles, and more. +Our vision is to empower you to add custom code to your server while maintaining the ability to use Amplication for updating your data model, changing permissions, adding roles, and more. Amplication achieves this by merging changes via our [Smart Git Sync](/smart-git-sync/) feature, based on pre-defined policies that allow you to add and update services, controllers, resolvers, and more without losing the link to Amplication. This approach gives you the freedom and power of custom code while saving time on repetitive tasks. -To do so, Amplication will merge changes via Git, based on pre-defined policies that will allow you to add and update services, controllers, resolvers, and more without losing the link to Amplication. You will have the freedom and power of code while saving time on repetitive tasks with Amplication. +## How It Works -:::info -This document describes the method to customize the server code only. +Your Amplication-generated application is structured to allow easy and maintainable customization, with a clear separation between customizable and non-customizable code. -Customizing the client application (Admin UI) code is not supported. You can use the generated client application as a boilerplate and keep developing it, but Amplication will not be able to merge your code changes with the newly generated code. +### Folder Structure -In case you decide to customize the client application, it is recommended to first clone the entire **Admin** folder to a separate folder or a separate repository and work on the cloned code instead of the original folder. -::: - -## How it works - -Your server application is created with a folder structure that allows easy and maintainable customization and development, with a clear separation between customizable code and non-customizable code. - -### The 'entity' folder - -Each entity has a dedicated folder under the 'src' folder. -For example: +Each entity has a dedicated folder under the 'src' folder, containing all necessary modules and files: ``` └── src - ├── customer - ├── user - ├── project - └── task + ├── customer + ├── user + ├── project + └── task ``` -The entity folder contains all the modules and files required to work with a specific entity, i.e. GraphQL resolver, REST API controller, service, and DTOs. +Within each entity folder, files are split into two groups: -The files are split into two groups: +1. **Base files**: Located in the 'base' folder, these are automatically generated by Amplication with every change. They should not be altered as they will be overwritten. -- Base files - the base files are the ones that are automatically generated by Amplication with every change. These files should not be altered or customized as they will be overwritten and the changes will not be preserved. All the base files exist in a separate folder named "base". - -- Customizable files - the customizable files inherit from the base files and they can be customized and will never be overwritten by Amplication. All the customizable files reside directly in the entity folder and can be freely customized and altered. +2. **Non-base Customizable files**: These inherit from the base files and can be safely customized. They reside directly in the entity folder. ``` src └── Customer ├── Base - │ ├── CreateCustomerArgs.ts - │ ├── CustomerFindManyArgs.ts - │ ├── CustomerFindUniqueArgs.ts - │ ├── customer.controller.base.spec.ts │ ├── customer.controller.base.ts - │ ├── customer.resolver.base.ts │ ├── customer.service.base.ts - │ ├── customer.ts - │ ├── CustomerCreateInput.ts - │ ├── CustomerUpdateInput.ts - │ ├── CustomerWhereInput.ts - │ ├── CustomerWhereUniqueInput.ts - │ ├── DeleteCustomerArgs.ts - │ └── updateCustomerArgs.ts - ├── customer.controller.spec.ts + │ └── ... ├── customer.controller.ts - ├── customer.module.ts - ├── customer.resolver.ts - └── customer.service.ts - + ├── customer.service.ts + └── ... ``` -### The 'base' folder +Amplication may still update the non-base files that include your custom code in certain circumstances. These updates are limited to changes necessary for preventing errors and ensuring the project can build correctly. For example, if you remove a plugin that was previously used in your service, Amplication might update the non-base files to remove references to the removed plugin, thus preventing build errors. + +This approach allows Amplication to maintain the integrity of your project structure while still preserving your custom code to the greatest extent possible. + +## Amplication's Approach to Custom Code + +Amplication is designed to preserve your custom code while allowing for continuous updates to the generated code. Here's how it works: + +1. **Initial Generation**: Amplication generates both base and customizable files for each module. + +2. **Subsequent Updates**: When you make changes in Amplication (e.g., updating the data model), it regenerates the base files and updates the customizable files as needed. + +3. **Smart Merging**: Amplication uses [Smart Git Sync](/smart-git-sync/) to merge changes, preserving your custom code while updating the generated parts. + +4. **Conflict Resolution**: If conflicts arise, Amplication provides clear indications and allows you to resolve them manually. -The base folder contains all the base files that are automatically generated by Amplication with every change. These files should not be altered or customized as they will be overwritten and the changes will not be preserved. +This approach allows you to freely add custom business logic, new endpoints, or any other customizations while still benefiting from Amplication's code generation and updates. -- _entity_.ts - the entity model class with all the model's properties -- _entity_.service.base.ts - the base service that wraps the Prisma client with all the CRUD operations on the entity. -- _entity_.controller.base.ts - the base REST API controller that provides all the CRUD operations on the entity. -- _entity_.resolver.base.ts - the base GraphQL resolver that provides all the queries and mutations on the entity. -- DTOs - Args and Input classes that are used for transferring data to and from the controller and resolver. +## Considerations -## Examples +- Customizing the client application (Admin UI) code is not currently supported within Amplication's regeneration process. If you need to customize the client, it's recommended to clone the entire **Admin** folder to a separate repository. +- While Amplication strives to maintain compatibility, major changes to your data model or entity structure may require manual updates to your custom code. -Following are some examples of how to add custom code in different layers of the application. +## Next Steps -The purpose of these examples is to get familiar with the layers' structure and the responsibility of each of the components in the server. +Now that you understand how custom code works in Amplication, you're ready to start adding your own business logic and customizations. For a step-by-step guide on how to add custom code to your service, check out our [How To Add Custom Code To Your Service](/getting-started/add-custom-code) guide. -- [Example: How to add business logic to a service](/custom-code/business-logic) -- [Example: How to add an action to a REST API controller](/custom-code/controller-action) -- [Example: How to add a query to a GraphQL resolver](/custom-code/graphql-query) +Happy coding! diff --git a/sidebars.js b/sidebars.js index 5070efe5..62909c92 100644 --- a/sidebars.js +++ b/sidebars.js @@ -27,6 +27,7 @@ const sidebars = { items: [ "getting-started/generated-app", // "getting-started/service-building-new-versions", + "how-to/custom-code-overview", "getting-started/view-generated-code", // "how-to/add-custom-code", "getting-started/authentication", From 10acf27405a265e6b1dea6ce01908a870473536c Mon Sep 17 00:00:00 2001 From: Derick Sozo Date: Tue, 10 Sep 2024 17:43:15 +0700 Subject: [PATCH 03/12] (docs): Adding more examples to the how to add custom code to your service guide. --- docs/getting-started/add-custom-code.md | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/docs/getting-started/add-custom-code.md b/docs/getting-started/add-custom-code.md index 189312bf..ee4f862f 100644 --- a/docs/getting-started/add-custom-code.md +++ b/docs/getting-started/add-custom-code.md @@ -213,6 +213,16 @@ Amplication will now rebuild your service, integrating your custom code with the Congratulations! You've successfully added custom code to implement a password reset feature in your Amplication-generated service. This custom logic will now be available through your API, allowing users to reset their passwords. +## More Custom Code Examples + +Here are more examples of how to add custom code in different layers of your service. + +The purpose of these examples is to get familiar with the structure and responsibility of each of the components in the server. + +- **Example**: [How to add business logic to a service](/custom-code/business-logic/) +- **Example**: [How to add an action to a REST API controller](/custom-code/controller-action/) +- **Example**: [How to add a query to a GraphQL resolver](/custom-code/graphql-query/) + ## Best Practices for Custom Code When adding custom code to your Amplication service, keep these best practices in mind: From bcf267bcc2b1b1391515ff094449021333fd6553 Mon Sep 17 00:00:00 2001 From: Derick Sozo Date: Tue, 10 Sep 2024 17:49:56 +0700 Subject: [PATCH 04/12] (docs): Fixing the build errors and changing the slug for the add custom code to your service page. --- docs/getting-started/add-custom-code.md | 2 +- docs/how-to/add-custom-code.md | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/docs/getting-started/add-custom-code.md b/docs/getting-started/add-custom-code.md index ee4f862f..fc7b5f96 100644 --- a/docs/getting-started/add-custom-code.md +++ b/docs/getting-started/add-custom-code.md @@ -2,7 +2,7 @@ id: add-custom-code title: How To Add Custom Code To Your Service sidebar_label: Add Custom Code To Your Service -slug: /how-to/add-custom-code-to-your-service +slug: /add-custom-code-to-your-service --- # How To Add Custom Code To Your Service diff --git a/docs/how-to/add-custom-code.md b/docs/how-to/add-custom-code.md index 4f200197..3197b4d5 100644 --- a/docs/how-to/add-custom-code.md +++ b/docs/how-to/add-custom-code.md @@ -32,9 +32,9 @@ Each entity has a dedicated folder under the 'src' folder, containing all necess Within each entity folder, files are split into two groups: -1. **Base files**: Located in the 'base' folder, these are automatically generated by Amplication with every change. They should not be altered as they will be overwritten. +1. **Base files**: Located in the 'base' folder, these are automatically generated by Amplication with every change. **They should not be altered as they will be overwritten with each new build**. -2. **Non-base Customizable files**: These inherit from the base files and can be safely customized. They reside directly in the entity folder. +2. **Non-base Customizable files**: These inherit from the base files and can be safely customized with your custom code. They reside directly in the entity folder. ``` src @@ -73,6 +73,6 @@ This approach allows you to freely add custom business logic, new endpoints, or ## Next Steps -Now that you understand how custom code works in Amplication, you're ready to start adding your own business logic and customizations. For a step-by-step guide on how to add custom code to your service, check out our [How To Add Custom Code To Your Service](/getting-started/add-custom-code) guide. +Now that you understand how custom code works in Amplication, you're ready to start adding your own business logic and customizations. For a step-by-step guide on how to add custom code to your service, check out our [How To Add Custom Code To Your Service](/add-custom-code-to-your-service) guide. Happy coding! From 331302dbad4ff55030240b1a904cdcdd83e83994 Mon Sep 17 00:00:00 2001 From: Derick Sozo Date: Tue, 10 Sep 2024 17:56:14 +0700 Subject: [PATCH 05/12] (docs): Making sure the broken link is fixed. --- docs/getting-started/generated-app.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/docs/getting-started/generated-app.md b/docs/getting-started/generated-app.md index 8dc1f082..a9205a11 100644 --- a/docs/getting-started/generated-app.md +++ b/docs/getting-started/generated-app.md @@ -93,4 +93,5 @@ For Node.js services, the Admin project provides a React application with ready- ## Learn more -- [How to add custom code to your application](/how-to/custom-code) +- [Understanding Custom Code in Amplication](/custom-code-overview/) +- [Add Custom Code To Your Service](/add-custom-code-to-your-service) From e6367191bd909deaf52867fdb8572c820aa65161 Mon Sep 17 00:00:00 2001 From: Derick Sozo Date: Wed, 18 Sep 2024 18:47:25 +0700 Subject: [PATCH 06/12] (docs): Implementing Paz's feedback. --- docs/getting-started/add-custom-code.md | 228 ++++++------------------ 1 file changed, 57 insertions(+), 171 deletions(-) diff --git a/docs/getting-started/add-custom-code.md b/docs/getting-started/add-custom-code.md index fc7b5f96..81e0ea1b 100644 --- a/docs/getting-started/add-custom-code.md +++ b/docs/getting-started/add-custom-code.md @@ -1,69 +1,64 @@ --- id: add-custom-code -title: How To Add Custom Code To Your Service -sidebar_label: Add Custom Code To Your Service +title: Adding Custom Code to Your Amplication Service +sidebar_label: Adding Custom Code slug: /add-custom-code-to-your-service --- -# How To Add Custom Code To Your Service +# Adding Custom Code to Your Amplication Service -While Amplication generates a robust, production-ready backend for your application, you'll often need to add custom business logic or additional functionality. This guide will walk you through the process of adding custom code to your Amplication-generated service while maintaining compatibility with future builds. +While Amplication generates a robust, production-ready backend for your application, you'll often need to add custom business logic or additional functionality. This guide explains how Amplication manages custom code alongside generated code, and provides best practices for adding your own code to an Amplication-generated service. ## Prerequisites -Before you begin, make sure you have: +Before you begin, make sure you know to: -1. [Created your first service](/first-service/) +1. [Create your first service](/first-service/) 2. [Set up entities](/set-up-entities/) for your service -3. [Configured roles and permissions](/configure-roles-and-permissions/) -4. [Added plugins to your service](/add-plugins-service/) -5. [Committed changes and built a new version](/commit-and-build-new-versions/) +3. [Configure roles and permissions](/configure-roles-and-permissions/) +4. [Adde plugins to your service](/add-plugins-service/) +5. [Commit changes and built a new version](/commit-and-build-new-versions/) +6. Read the [Understanding Custom Code in Amplication](/how-to/custom-code/) document ## Understanding Custom Code in Amplication -When adding custom code to your Amplication-generated service, it's important to understand how Amplication manages and preserves your changes: +Amplication is designed to allow seamless integration of custom code with generated code through our [Smart Git Sync](/smart-git-sync) feature: -1. Custom code is added to specific files that Amplication recognizes and preserves during rebuilds. -2. You'll work directly in your git repository, making changes to the generated code. -3. Amplication uses a folder structure that separates customizable and non-customizable code. -4. The `base` folder contains files that should not be modified, as they will be overwritten by Amplication. -5. Files outside the `base` folder can be safely customized and will be preserved across builds. +1. All code in your Amplication project can be customized. +2. Amplication uses a specific folder structure to manage custom and generated code. +3. The `base` folder contains generated files that Amplication updates with each build. +4. Files outside the `base` folder are intended for your custom code and are preserved across builds. +5. Amplication uses [smart merging](/smart-git-sync) to update your project while preserving your custom code. -Let's walk through the process of adding custom code to implement a password reset feature for the User entity. +## How Amplication Handles Custom Code -## Step 1: Merge the Amplication Branch +Amplication preserves your custom code during updates: -First, ensure that your local repository is up-to-date with the latest Amplication-generated code: +1. Base files in the `base` folder are regenerated with each build. +2. Non-base files (like `user.service.ts`) are preserved during updates. +3. If necessary changes to non-base files are required (e.g., removing references to a deleted plugin), Amplication will make these changes automatically while preserving your custom code. -1. Open your terminal and navigate to your project's root directory. -2. Switch to your main branch: - ```bash - git checkout main - ``` -3. Pull the latest changes: - ```bash - git pull origin main - ``` -4. Merge the `amplication` branch into your main branch: - ```bash - git merge amplication - ``` -5. Push the merged changes to your remote repository: - ```bash - git push origin main - ``` +## Adding Custom Code: A Simple Example -## Step 2: Create a New Branch for Custom Code +Let's walk through a simple example of adding custom code to your service. -Create a new branch from the main branch to make your custom code changes: +### Step 1: Create A New Feature Branch + +Ensure that your local repository is up-to-date with the latest Amplication-generated code: + +```bash +git checkout main && git merge amplication && git push origin main +``` + +Next, create a new branch from the main branch to make your custom code changes: ```bash -git checkout -b feature/password-reset main +git checkout -b feature/user-full-name ``` -## Step 3: Locate the Correct Files +### Step 2: Locate the Correct Files -Navigate to your service's `src` folder. You'll find a folder for each entity. In this case, we'll be working with the `user` folder: +Navigate to your service's `src` folder and find the `user` folder: ``` src @@ -78,169 +73,60 @@ src └── user.service.ts ``` -We'll be modifying `user.service.ts` and `user.controller.ts` to add our custom password reset functionality. +We'll be modifying `user.service.ts` to add our custom functionality. -## Step 4: Add Custom Logic to the Service +### Step 3: Add Custom Logic to the Service Open `src/user/user.service.ts`. This file extends the base service and is where we'll add our custom method. -1. Add the necessary imports at the top of the file: - ```typescript import { Injectable } from "@nestjs/common"; -import { PrismaService } from "nestjs-prisma"; import { UserServiceBase } from "./base/user.service.base"; -import { PasswordService } from "../auth/password.service"; -import { User } from "./base/User"; -import { UserWhereUniqueInput } from "./base/UserWhereUniqueInput"; -``` - -2. Add the custom `resetPassword` method to the `UserService` class: -```typescript @Injectable() export class UserService extends UserServiceBase { - constructor( - protected readonly prisma: PrismaService, - protected readonly passwordService: PasswordService - ) { - super(prisma, passwordService); - } - - async resetPassword(args: UserWhereUniqueInput): Promise { - const newPassword = Math.random().toString(36).slice(-8); // Generate a random password - const hashedPassword = await this.passwordService.hashPassword(newPassword); - - const updatedUser = await this.prisma.user.update({ - where: args, - data: { - password: hashedPassword - } - }); - - // In a real-world scenario, you'd want to send this password to the user securely - console.log(`New password for user ${updatedUser.id}: ${newPassword}`); - - return updatedUser; + async getUserFullName(userId: string): Promise { + const user = await this.findOne({ where: { id: userId } }); + return `${user.firstName} ${user.lastName}`; } } ``` -## Step 5: Add a New Endpoint to the Controller - -Now, let's add a new endpoint to the User controller to expose our password reset functionality. Open `src/user/user.controller.ts`: - -1. Add the necessary imports at the top of the file: - -```typescript -import * as common from "@nestjs/common"; -import * as swagger from "@nestjs/swagger"; -import * as nestAccessControl from "nest-access-control"; -import { UserService } from "./user.service"; -import { UserControllerBase } from "./base/user.controller.base"; -import { User } from "./base/User"; -import { UserWhereUniqueInput } from "./base/UserWhereUniqueInput"; -import { AclValidateRequestInterceptor } from "../interceptors/aclValidateRequest.interceptor"; -``` - -2. Add the new `resetPassword` endpoint to the `UserController` class: - -```typescript -@swagger.ApiTags("users") -@common.Controller("users") -export class UserController extends UserControllerBase { - constructor( - protected readonly service: UserService, - @nestAccessControl.InjectRolesBuilder() - protected readonly rolesBuilder: nestAccessControl.RolesBuilder - ) { - super(service, rolesBuilder); - } - - @common.UseInterceptors(AclValidateRequestInterceptor) - @common.Patch("/:id/reset-password") - @nestAccessControl.UseRoles({ - resource: "User", - action: "update", - possession: "own", - }) - @swagger.ApiOkResponse({ type: User }) - @swagger.ApiNotFoundResponse({ type: errors.NotFoundException }) - @swagger.ApiForbiddenResponse({ type: errors.ForbiddenException }) - async resetPassword( - @common.Param() params: UserWhereUniqueInput - ): Promise { - return this.service.resetPassword(params); - } -} -``` +This example adds a simple method to get a user's full name. Note how it uses the `findOne` method from the base service. -## Step 6: Commit and Push Your Changes +### Step 4: Push Your Changes After adding your custom code, commit the changes to your git repository: ```bash git add . -git commit -m "Added custom password reset functionality" -git push origin feature/password-reset +git commit -m "Added full name functionality" +git push origin feature/user-full-name ``` -## Step 7: Create a Pull Request - -Go to your repository on GitHub (or your chosen git provider) and create a new pull request: - -1. Set the base branch to `main` -2. Set the compare branch to `feature/password-reset` -3. Give your pull request a descriptive title and description -4. Create the pull request - -## Step 8: Merge the Pull Request - -After reviewing your changes, merge the pull request into the main branch. This step integrates your custom code with the main codebase. - -## Step 9: Rebuild Your Service in Amplication - -Now that you've added custom code to your repository and merged it into the main branch, you need to rebuild your service in Amplication to ensure everything works together: +After going through any review process, merge the feature branch into your working branch: -1. Go to your service in the Amplication web interface. -2. Click on "Commit Changes & Build" in the right sidebar. -3. In the commit message, write "Integrated custom password reset functionality". -4. Click "Commit Changes & Build" to start the build process. - -Amplication will now rebuild your service, integrating your custom code with the generated code. - -## You're Done! - -Congratulations! You've successfully added custom code to implement a password reset feature in your Amplication-generated service. This custom logic will now be available through your API, allowing users to reset their passwords. - -## More Custom Code Examples - -Here are more examples of how to add custom code in different layers of your service. - -The purpose of these examples is to get familiar with the structure and responsibility of each of the components in the server. - -- **Example**: [How to add business logic to a service](/custom-code/business-logic/) -- **Example**: [How to add an action to a REST API controller](/custom-code/controller-action/) -- **Example**: [How to add a query to a GraphQL resolver](/custom-code/graphql-query/) +```bash +git checkout main && git merge feature/user-full-name && git push origin main +``` ## Best Practices for Custom Code When adding custom code to your Amplication service, keep these best practices in mind: -1. Always add custom code to the non-base files (e.g., `user.service.ts` instead of `user.service.base.ts`). -2. Use the types and interfaces generated by Amplication to ensure type safety. -3. Leverage the existing services and utilities provided by Amplication (like `PasswordService` in this example). -4. Document your custom code to make it easier for team members to understand and maintain. -5. Always create a new branch for your custom code changes. -6. Regularly merge the `amplication` branch into your main branch to stay up-to-date with Amplication-generated changes. +1. Add custom code to non-base files (e.g., `user.service.ts` instead of `user.service.base.ts`). +2. Use types and interfaces generated by Amplication to ensure type safety. +3. Leverage existing services and utilities provided by Amplication. +4. Document your custom code thoroughly. +5. Create a new branch for significant custom code changes. +6. Regularly pull and merge the latest Amplication-generated code from the `amplication` branch into your working branch. ## Next Steps -Now that you know how to add custom code to your Amplication service, you can extend its functionality in various ways: +Now that you know how to add custom code to your Amplication service, you can: - Implement complex business logic specific to your application -- Add custom API endpoints for specialized operations +- Extend generated services with additional methods +- Create custom utilities and helpers - Integrate with external services or APIs - Implement advanced validation and data processing - -Amplication is designed to be flexible, allowing you to leverage its powerful code generation while still giving you the freedom to customize your service as needed. From 6d936b82f935d59d595cc566db56c7a142049399 Mon Sep 17 00:00:00 2001 From: Derick Sozo Date: Wed, 18 Sep 2024 18:50:59 +0700 Subject: [PATCH 07/12] (docs): Fixing the error. --- docs/getting-started/add-custom-code.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/getting-started/add-custom-code.md b/docs/getting-started/add-custom-code.md index 81e0ea1b..b3d54280 100644 --- a/docs/getting-started/add-custom-code.md +++ b/docs/getting-started/add-custom-code.md @@ -16,8 +16,8 @@ Before you begin, make sure you know to: 1. [Create your first service](/first-service/) 2. [Set up entities](/set-up-entities/) for your service 3. [Configure roles and permissions](/configure-roles-and-permissions/) -4. [Adde plugins to your service](/add-plugins-service/) -5. [Commit changes and built a new version](/commit-and-build-new-versions/) +4. [Add plugins to your service](/add-plugins-service/) +5. [Commit changes and build a new version](/commit-and-build-new-versions/) 6. Read the [Understanding Custom Code in Amplication](/how-to/custom-code/) document ## Understanding Custom Code in Amplication @@ -36,7 +36,7 @@ Amplication preserves your custom code during updates: 1. Base files in the `base` folder are regenerated with each build. 2. Non-base files (like `user.service.ts`) are preserved during updates. -3. If necessary changes to non-base files are required (e.g., removing references to a deleted plugin), Amplication will make these changes automatically while preserving your custom code. +3. If necessary, changes to non-base files are required (e.g., removing references to a deleted plugin), Amplication will make these changes automatically while preserving your custom code. ## Adding Custom Code: A Simple Example From 8fd6f3ebcb527f9535641cabbd1bd2600a37e0d3 Mon Sep 17 00:00:00 2001 From: Derick Sozo Date: Thu, 19 Sep 2024 09:11:34 +0700 Subject: [PATCH 08/12] (docs): Re-writing the original understanding custom code page. Fixing the link on the new guide. --- docs/getting-started/add-custom-code.md | 5 ++- docs/how-to/add-custom-code.md | 54 ++++++++++++++----------- 2 files changed, 35 insertions(+), 24 deletions(-) diff --git a/docs/getting-started/add-custom-code.md b/docs/getting-started/add-custom-code.md index b3d54280..85649448 100644 --- a/docs/getting-started/add-custom-code.md +++ b/docs/getting-started/add-custom-code.md @@ -18,7 +18,6 @@ Before you begin, make sure you know to: 3. [Configure roles and permissions](/configure-roles-and-permissions/) 4. [Add plugins to your service](/add-plugins-service/) 5. [Commit changes and build a new version](/commit-and-build-new-versions/) -6. Read the [Understanding Custom Code in Amplication](/how-to/custom-code/) document ## Understanding Custom Code in Amplication @@ -30,6 +29,10 @@ Amplication is designed to allow seamless integration of custom code with genera 4. Files outside the `base` folder are intended for your custom code and are preserved across builds. 5. Amplication uses [smart merging](/smart-git-sync) to update your project while preserving your custom code. +:::note +For more a more in-depth explanation, read [Understanding Custom Code in Amplication](/custom-code-overview/) +::: + ## How Amplication Handles Custom Code Amplication preserves your custom code during updates: diff --git a/docs/how-to/add-custom-code.md b/docs/how-to/add-custom-code.md index 3197b4d5..30a9d7c3 100644 --- a/docs/how-to/add-custom-code.md +++ b/docs/how-to/add-custom-code.md @@ -8,19 +8,19 @@ pagination_next: getting-started/add-custom-code # Understanding Custom Code in Amplication -This page provides an overview of how custom code works in Amplication and our vision for seamless integration between generated and custom code. - -## The Vision - -Our vision is to empower you to add custom code to your server while maintaining the ability to use Amplication for updating your data model, changing permissions, adding roles, and more. Amplication achieves this by merging changes via our [Smart Git Sync](/smart-git-sync/) feature, based on pre-defined policies that allow you to add and update services, controllers, resolvers, and more without losing the link to Amplication. This approach gives you the freedom and power of custom code while saving time on repetitive tasks. +Amplication allows seamless integration of custom code with generated code, empowering you to add custom business logic while continuing to use Amplication for updating your data model, permissions, roles, and more. ## How It Works -Your Amplication-generated application is structured to allow easy and maintainable customization, with a clear separation between customizable and non-customizable code. +Amplication uses a specific folder structure and smart merging using [Smart Git Sync](/smart-git-sync) to manage custom and generated code: + +1. All code in your Amplication project can be customized. +2. Amplication generates a folder structure that separates base files from non-base files intended for custom code. +3. Updates to your Amplication configuration regenerate base files while preserving your custom code. ### Folder Structure -Each entity has a dedicated folder under the 'src' folder, containing all necessary modules and files: +Each entity has a dedicated folder under the `src` folder: ``` └── src @@ -32,9 +32,9 @@ Each entity has a dedicated folder under the 'src' folder, containing all necess Within each entity folder, files are split into two groups: -1. **Base files**: Located in the 'base' folder, these are automatically generated by Amplication with every change. **They should not be altered as they will be overwritten with each new build**. +1. **Base files**: Located in the 'base' folder, these are automatically generated by Amplication with every build. While these can be modified, changes to these files may be lost in subsequent builds. -2. **Non-base Customizable files**: These inherit from the base files and can be safely customized with your custom code. They reside directly in the entity folder. +2. **Non-base files**: These inherit from the base files and are intended for your custom code. They reside directly in the entity folder and your custom code is preserved across builds. ``` src @@ -48,31 +48,39 @@ src └── ... ``` -Amplication may still update the non-base files that include your custom code in certain circumstances. These updates are limited to changes necessary for preventing errors and ensuring the project can build correctly. For example, if you remove a plugin that was previously used in your service, Amplication might update the non-base files to remove references to the removed plugin, thus preventing build errors. - -This approach allows Amplication to maintain the integrity of your project structure while still preserving your custom code to the greatest extent possible. +## Smart Git Sync -## Amplication's Approach to Custom Code +Amplication uses [Smart Git Sync](/smart-git-sync/) to merge changes, preserving your custom code while updating generated parts. This feature: -Amplication is designed to preserve your custom code while allowing for continuous updates to the generated code. Here's how it works: +1. Regenerates base files with each build. +2. Preserves non-base files containing your custom code. +3. Makes necessary updates to non-base files (e.g., removing references to deleted plugins) while maintaining your custom code. -1. **Initial Generation**: Amplication generates both base and customizable files for each module. +## Best Practices for Custom Code -2. **Subsequent Updates**: When you make changes in Amplication (e.g., updating the data model), it regenerates the base files and updates the customizable files as needed. +1. Add custom code to non-base files (e.g., `user.service.ts` instead of `user.service.base.ts`). +2. Use types and interfaces generated by Amplication to ensure type safety. +3. Leverage existing services and utilities provided by Amplication. +4. Document your custom code thoroughly. +5. Create a new branch for significant custom code changes. +6. Regularly pull and merge the latest Amplication-generated code into your working branch. -3. **Smart Merging**: Amplication uses [Smart Git Sync](/smart-git-sync/) to merge changes, preserving your custom code while updating the generated parts. +## Handling Conflicts -4. **Conflict Resolution**: If conflicts arise, Amplication provides clear indications and allows you to resolve them manually. +While Amplication strives to preserve your custom code, conflicts may arise, especially with significant changes to your data model or entity structure. If conflicts occur: -This approach allows you to freely add custom business logic, new endpoints, or any other customizations while still benefiting from Amplication's code generation and updates. +1. Amplication will provide clear indications of the conflicting areas. +2. You may need to manually resolve these conflicts, merging your custom code with the updated generated code. +3. After resolving conflicts, thoroughly test your application to ensure everything works as expected. ## Considerations -- Customizing the client application (Admin UI) code is not currently supported within Amplication's regeneration process. If you need to customize the client, it's recommended to clone the entire **Admin** folder to a separate repository. -- While Amplication strives to maintain compatibility, major changes to your data model or entity structure may require manual updates to your custom code. +- While all code can be customized, we recommend focusing custom code in the non-base files for easier maintenance. +- Major changes to your data model or entity structure may require manual updates to your custom code. +- Client-side customization (Admin UI) is supported, but changes may not be automatically merged in future builds. Consider maintaining a separate repository for extensive client-side customizations. ## Next Steps -Now that you understand how custom code works in Amplication, you're ready to start adding your own business logic and customizations. For a step-by-step guide on how to add custom code to your service, check out our [How To Add Custom Code To Your Service](/add-custom-code-to-your-service) guide. +Now that you understand how custom code works in Amplication, you're ready to start adding your own business logic and customizations. For a step-by-step guide, check out our [How To Add Custom Code To Your Service](/add-custom-code-to-your-service) guide. -Happy coding! +Happy coding! \ No newline at end of file From 196dbc6122f9b096f4c157f0d4797630219859bc Mon Sep 17 00:00:00 2001 From: Derick Sozo Date: Mon, 23 Sep 2024 13:57:07 +0700 Subject: [PATCH 09/12] (docs): Implementing all of Paz's latest feedback. --- docs/getting-started/add-custom-code.md | 34 ++---------------- docs/how-to/add-custom-code.md | 48 ++++++++++++++----------- 2 files changed, 30 insertions(+), 52 deletions(-) diff --git a/docs/getting-started/add-custom-code.md b/docs/getting-started/add-custom-code.md index 85649448..ed89dc0b 100644 --- a/docs/getting-started/add-custom-code.md +++ b/docs/getting-started/add-custom-code.md @@ -19,28 +19,10 @@ Before you begin, make sure you know to: 4. [Add plugins to your service](/add-plugins-service/) 5. [Commit changes and build a new version](/commit-and-build-new-versions/) -## Understanding Custom Code in Amplication - -Amplication is designed to allow seamless integration of custom code with generated code through our [Smart Git Sync](/smart-git-sync) feature: - -1. All code in your Amplication project can be customized. -2. Amplication uses a specific folder structure to manage custom and generated code. -3. The `base` folder contains generated files that Amplication updates with each build. -4. Files outside the `base` folder are intended for your custom code and are preserved across builds. -5. Amplication uses [smart merging](/smart-git-sync) to update your project while preserving your custom code. - :::note For more a more in-depth explanation, read [Understanding Custom Code in Amplication](/custom-code-overview/) ::: -## How Amplication Handles Custom Code - -Amplication preserves your custom code during updates: - -1. Base files in the `base` folder are regenerated with each build. -2. Non-base files (like `user.service.ts`) are preserved during updates. -3. If necessary, changes to non-base files are required (e.g., removing references to a deleted plugin), Amplication will make these changes automatically while preserving your custom code. - ## Adding Custom Code: A Simple Example Let's walk through a simple example of adding custom code to your service. @@ -50,7 +32,7 @@ Let's walk through a simple example of adding custom code to your service. Ensure that your local repository is up-to-date with the latest Amplication-generated code: ```bash -git checkout main && git merge amplication && git push origin main +git checkout main && git merge amplication && git push ``` Next, create a new branch from the main branch to make your custom code changes: @@ -110,26 +92,14 @@ git push origin feature/user-full-name After going through any review process, merge the feature branch into your working branch: ```bash -git checkout main && git merge feature/user-full-name && git push origin main +git checkout main && git merge feature/user-full-name && git push ``` -## Best Practices for Custom Code - -When adding custom code to your Amplication service, keep these best practices in mind: - -1. Add custom code to non-base files (e.g., `user.service.ts` instead of `user.service.base.ts`). -2. Use types and interfaces generated by Amplication to ensure type safety. -3. Leverage existing services and utilities provided by Amplication. -4. Document your custom code thoroughly. -5. Create a new branch for significant custom code changes. -6. Regularly pull and merge the latest Amplication-generated code from the `amplication` branch into your working branch. - ## Next Steps Now that you know how to add custom code to your Amplication service, you can: - Implement complex business logic specific to your application -- Extend generated services with additional methods - Create custom utilities and helpers - Integrate with external services or APIs - Implement advanced validation and data processing diff --git a/docs/how-to/add-custom-code.md b/docs/how-to/add-custom-code.md index 30a9d7c3..00e3c1a1 100644 --- a/docs/how-to/add-custom-code.md +++ b/docs/how-to/add-custom-code.md @@ -8,17 +8,21 @@ pagination_next: getting-started/add-custom-code # Understanding Custom Code in Amplication -Amplication allows seamless integration of custom code with generated code, empowering you to add custom business logic while continuing to use Amplication for updating your data model, permissions, roles, and more. +Amplication allows seamless integration of your custom code with generated code through our [Smart Git Sync](/smart-git-sync) feature. -## How It Works +This lets you add custom business logic while continuing to use Amplication to update your data models, permissions, roles, plugins, and more. -Amplication uses a specific folder structure and smart merging using [Smart Git Sync](/smart-git-sync) to manage custom and generated code: +## How Custom Code Integration Works -1. All code in your Amplication project can be customized. -2. Amplication generates a folder structure that separates base files from non-base files intended for custom code. -3. Updates to your Amplication configuration regenerate base files while preserving your custom code. +1. Custom code can be added to _all files_ in your Amplication project. +2. Amplication uses a specific folder structure to manage base and non-base files. +3. The `base` folder contains generated files that will get updates only if there are relevant changes. +4. Non-base files are intended for custom code. +5. If necessary changes to non-base files are required (e.g., removing references to a deleted plugin), Amplication will make these changes automatically. -### Folder Structure +Amplication always respects your custom code and syncs it with the generated code in both base and non-base files. + +## Folder Structure Each entity has a dedicated folder under the `src` folder: @@ -32,9 +36,9 @@ Each entity has a dedicated folder under the `src` folder: Within each entity folder, files are split into two groups: -1. **Base files**: Located in the 'base' folder, these are automatically generated by Amplication with every build. While these can be modified, changes to these files may be lost in subsequent builds. +1. **Base files**: Located in the `base` folder, these are automatically generated by Amplication. -2. **Non-base files**: These inherit from the base files and are intended for your custom code. They reside directly in the entity folder and your custom code is preserved across builds. +2. **Non-base files**: These inherit from the base files and are intended for your custom code. They reside directly in the entity folder. Your custom code is always preserved and respected across builds. ``` src @@ -50,37 +54,41 @@ src ## Smart Git Sync -Amplication uses [Smart Git Sync](/smart-git-sync/) to merge changes, preserving your custom code while updating generated parts. This feature: +Amplication uses [Smart Git Sync](/smart-git-sync/) to seamlessly integrate changes, preserving your custom code while updating the generated parts. This feature: + +1. Preserves and always respects custom code in base and non-base files. +2. Makes necessary updates to non-base ,files (e.g., removing references to deleted plugins) while maintaining your custom code. -1. Regenerates base files with each build. -2. Preserves non-base files containing your custom code. -3. Makes necessary updates to non-base files (e.g., removing references to deleted plugins) while maintaining your custom code. +:::note +For a more in-depth explanation, please see the [Smart Git Sync](/smart-git-sync) page. +::: ## Best Practices for Custom Code +When adding custom code to your Amplication service, keep these best practices in mind: + 1. Add custom code to non-base files (e.g., `user.service.ts` instead of `user.service.base.ts`). 2. Use types and interfaces generated by Amplication to ensure type safety. 3. Leverage existing services and utilities provided by Amplication. 4. Document your custom code thoroughly. 5. Create a new branch for significant custom code changes. -6. Regularly pull and merge the latest Amplication-generated code into your working branch. +6. Regularly pull and merge the latest Amplication-generated code from the `amplication` branch into your working branch. ## Handling Conflicts While Amplication strives to preserve your custom code, conflicts may arise, especially with significant changes to your data model or entity structure. If conflicts occur: -1. Amplication will provide clear indications of the conflicting areas. -2. You may need to manually resolve these conflicts, merging your custom code with the updated generated code. -3. After resolving conflicts, thoroughly test your application to ensure everything works as expected. +1. Amplication will provide clear indications of the conflicting areas using git diffs in your chosen git provider. +2. You may need to manually resolve these conflicts in the `amplication` branch. +3. After resolving conflicts, merging the updated `amplication` branch into the main branch. ## Considerations -- While all code can be customized, we recommend focusing custom code in the non-base files for easier maintenance. +- While all code can be customized, we recommend adding custom code in the non-base files for easier maintenance. - Major changes to your data model or entity structure may require manual updates to your custom code. -- Client-side customization (Admin UI) is supported, but changes may not be automatically merged in future builds. Consider maintaining a separate repository for extensive client-side customizations. ## Next Steps Now that you understand how custom code works in Amplication, you're ready to start adding your own business logic and customizations. For a step-by-step guide, check out our [How To Add Custom Code To Your Service](/add-custom-code-to-your-service) guide. -Happy coding! \ No newline at end of file +Happy coding! From 25516bd724fb20c324909cd75d7de7f8f2786bf9 Mon Sep 17 00:00:00 2001 From: Derick Sozo Date: Mon, 23 Sep 2024 17:10:12 +0700 Subject: [PATCH 10/12] (docs): After the call, I have a much better understanding of this. Implementing Paz's feedback, making these pages much easier to read, and flow better. --- docs/getting-started/add-custom-code.md | 29 +++++++----- docs/how-to/add-custom-code.md | 61 +++++++++++++------------ 2 files changed, 49 insertions(+), 41 deletions(-) diff --git a/docs/getting-started/add-custom-code.md b/docs/getting-started/add-custom-code.md index ed89dc0b..798fc1e9 100644 --- a/docs/getting-started/add-custom-code.md +++ b/docs/getting-started/add-custom-code.md @@ -1,13 +1,14 @@ --- id: add-custom-code title: Adding Custom Code to Your Amplication Service -sidebar_label: Adding Custom Code +sidebar_label: Add Custom Code To Your Service slug: /add-custom-code-to-your-service --- -# Adding Custom Code to Your Amplication Service +# Add Custom Code To Your Service -While Amplication generates a robust, production-ready backend for your application, you'll often need to add custom business logic or additional functionality. This guide explains how Amplication manages custom code alongside generated code, and provides best practices for adding your own code to an Amplication-generated service. +Amplication generates a robust, production-ready backend for your app, but you'll often need to add your own custom business logic with custom code. +In this guide you'll learn how to add custom code to your Amplication service with a simple example. ## Prerequisites @@ -20,12 +21,13 @@ Before you begin, make sure you know to: 5. [Commit changes and build a new version](/commit-and-build-new-versions/) :::note -For more a more in-depth explanation, read [Understanding Custom Code in Amplication](/custom-code-overview/) +For more a more in-depth explanation of how custom code works, read [Understanding Custom Code in Amplication](/custom-code-overview/). ::: -## Adding Custom Code: A Simple Example +## Adding Custom Code: Retrieve The User's Full Name Let's walk through a simple example of adding custom code to your service. +In this example, we'll add a method with custom code to get the user's full name. ### Step 1: Create A New Feature Branch @@ -41,9 +43,9 @@ Next, create a new branch from the main branch to make your custom code changes: git checkout -b feature/user-full-name ``` -### Step 2: Locate the Correct Files +### Step 2: Locate the Correct File -Navigate to your service's `src` folder and find the `user` folder: +Navigate to the code of your generated service's `src` folder and find the `user` folder: ``` src @@ -58,11 +60,16 @@ src └── user.service.ts ``` -We'll be modifying `user.service.ts` to add our custom functionality. +We'll modify the `user.service.ts` to add our custom functionality. + +:::tip +Notice that we're adding our changes to `user.service.ts` instead of `base/user.service.base.ts` file. +To learn more why we recommend doing this, read [Understanding Custom Code in Amplication](/custom-code-overview/). +::: ### Step 3: Add Custom Logic to the Service -Open `src/user/user.service.ts`. This file extends the base service and is where we'll add our custom method. +Open `src/user/user.service.ts`. This file extends the base service and is where we'll add our custom method that retrieves the user's full name. ```typescript import { Injectable } from "@nestjs/common"; @@ -77,11 +84,11 @@ export class UserService extends UserServiceBase { } ``` -This example adds a simple method to get a user's full name. Note how it uses the `findOne` method from the base service. +Note how it uses the `findOne` method from the base service. ### Step 4: Push Your Changes -After adding your custom code, commit the changes to your git repository: +After adding your custom code, commit the changes to the git feature branch you created in Step 1: ```bash git add . diff --git a/docs/how-to/add-custom-code.md b/docs/how-to/add-custom-code.md index 00e3c1a1..5a443cfa 100644 --- a/docs/how-to/add-custom-code.md +++ b/docs/how-to/add-custom-code.md @@ -9,18 +9,20 @@ pagination_next: getting-started/add-custom-code # Understanding Custom Code in Amplication Amplication allows seamless integration of your custom code with generated code through our [Smart Git Sync](/smart-git-sync) feature. - This lets you add custom business logic while continuing to use Amplication to update your data models, permissions, roles, plugins, and more. +This guide is an in-depth explanation on how custom code works in your Amplication project. + ## How Custom Code Integration Works -1. Custom code can be added to _all files_ in your Amplication project. -2. Amplication uses a specific folder structure to manage base and non-base files. -3. The `base` folder contains generated files that will get updates only if there are relevant changes. -4. Non-base files are intended for custom code. -5. If necessary changes to non-base files are required (e.g., removing references to a deleted plugin), Amplication will make these changes automatically. +1. Amplication uses a specific folder structure to manage base and non-base files. +2. The `base` folder contains generated files that will get updates only if there are relevant changes (e.g., you add a new plugin). +3. Non-base files are intended for custom code. +4. Amplication will make necessary changes to both base and non-base files (e.g., updating interfaces, removing references to deleted plugins) while always preserving and respecting your custom code. -Amplication always respects your custom code and syncs it with the generated code in both base and non-base files. +:::tip +While you can add custom code to _all files_, we recommend primarily adding custom code to non-base files (e.g., `user.service.ts` instead of `user.service.base.ts`) for easier maintenance. +::: ## Folder Structure @@ -36,9 +38,13 @@ Each entity has a dedicated folder under the `src` folder: Within each entity folder, files are split into two groups: -1. **Base files**: Located in the `base` folder, these are automatically generated by Amplication. +### Base files + +**Base files**: Located in the `base` folder, these are automatically generated by Amplication. + +### Non-base Files -2. **Non-base files**: These inherit from the base files and are intended for your custom code. They reside directly in the entity folder. Your custom code is always preserved and respected across builds. +**Non-base files**: These inherit from the base files and are intended for your custom code. They reside directly in the entity folder. ``` src @@ -52,43 +58,38 @@ src └── ... ``` +Your custom code, whether it's in base or non-file files, is always preserved and respected across builds. + ## Smart Git Sync Amplication uses [Smart Git Sync](/smart-git-sync/) to seamlessly integrate changes, preserving your custom code while updating the generated parts. This feature: -1. Preserves and always respects custom code in base and non-base files. -2. Makes necessary updates to non-base ,files (e.g., removing references to deleted plugins) while maintaining your custom code. +Makes necessary updates to both base and non-base files (e.g., updating interfaces, removing references to deleted plugins) while respecting your custom code. :::note -For a more in-depth explanation, please see the [Smart Git Sync](/smart-git-sync) page. +For a more in-depth explanation, please read the [Smart Git Sync](/smart-git-sync) page. ::: ## Best Practices for Custom Code When adding custom code to your Amplication service, keep these best practices in mind: -1. Add custom code to non-base files (e.g., `user.service.ts` instead of `user.service.base.ts`). -2. Use types and interfaces generated by Amplication to ensure type safety. -3. Leverage existing services and utilities provided by Amplication. -4. Document your custom code thoroughly. -5. Create a new branch for significant custom code changes. -6. Regularly pull and merge the latest Amplication-generated code from the `amplication` branch into your working branch. - -## Handling Conflicts +1. Use types and interfaces generated by Amplication to ensure type safety. +2. Leverage existing services and utilities provided by Amplication. +3. Create a new feature branch for significant custom code changes. +4. Regularly pull and merge the latest Amplication-generated code from the `amplication` branch into your working branch (e.g., `main`). -While Amplication strives to preserve your custom code, conflicts may arise, especially with significant changes to your data model or entity structure. If conflicts occur: +## How To Handle Conflicts -1. Amplication will provide clear indications of the conflicting areas using git diffs in your chosen git provider. -2. You may need to manually resolve these conflicts in the `amplication` branch. -3. After resolving conflicts, merging the updated `amplication` branch into the main branch. +While Amplication strives to preserve your custom code, conflicts may arise, especially with significant changes to your data model or entity structure. -## Considerations +If conflicts arise during this process, you'll need to resolve them manually in the `amplication` branch before merging into your main branch. -- While all code can be customized, we recommend adding custom code in the non-base files for easier maintenance. -- Major changes to your data model or entity structure may require manual updates to your custom code. +1. Amplication will provide clear indications of the conflicting areas using git diffs in your chosen git provider. +2. You'll need to manually resolve these conflicts in the `amplication` branch. +3. After resolving conflicts, merge the updated `amplication` branch into the main branch. ## Next Steps -Now that you understand how custom code works in Amplication, you're ready to start adding your own business logic and customizations. For a step-by-step guide, check out our [How To Add Custom Code To Your Service](/add-custom-code-to-your-service) guide. - -Happy coding! +Now that you understand how custom code works in Amplication, you're ready to start adding your own business logic. +For a step-by-step guide, check out our [How To Add Custom Code To Your Service](/add-custom-code-to-your-service) guide. From 14d9ca6eaaf231f2b961d234789970a74b1fc9b5 Mon Sep 17 00:00:00 2001 From: Derick Ruiz Date: Wed, 4 Dec 2024 16:19:52 +0700 Subject: [PATCH 11/12] (docs): Adding a redirect for the new custom code page. --- docusaurus.config.js | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/docusaurus.config.js b/docusaurus.config.js index 7499b89d..b011bd08 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -198,6 +198,10 @@ module.exports = { "@docusaurus/plugin-client-redirects", { redirects: [ + { + to: "/add-custom-code-to-your-service" + from: ["/how-to/custom-code/"] + }, { to: "/plugins/guides/authentication", from: ["/authentication-plugin-examples"] From c86dfa58cb68477776d83d7804d439c5f535cabb Mon Sep 17 00:00:00 2001 From: Derick Ruiz Date: Wed, 4 Dec 2024 16:25:20 +0700 Subject: [PATCH 12/12] (docs): Fixing the syntax error. --- docusaurus.config.js | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docusaurus.config.js b/docusaurus.config.js index b011bd08..f4e7e005 100644 --- a/docusaurus.config.js +++ b/docusaurus.config.js @@ -199,7 +199,7 @@ module.exports = { { redirects: [ { - to: "/add-custom-code-to-your-service" + to: "/add-custom-code-to-your-service", from: ["/how-to/custom-code/"] }, {