kaushalendra pandey
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee

      This note has no invitees

    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Note Insights New
    • Engagement control
    • Make a copy
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Note Insights Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Make a copy Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee

    This note has no invitees

  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       Owned this note    Owned this note      
    Published Linked with GitHub
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    # LAMBDAS AND API # **Naming the lambda functions:** - We will be following **snake case** for naming the lambdas. While naming the lambda, we can use the verbs, i.e. **get, create, update**, etc. The convention would be as follows: > ✅ **webd_serviceName_functionName** Ex. **webd_learning_checkPremiumUser.** This lambda function is for checking if the user is premium or not. Here the name of the service is learning and name of the API is *checkPremiumUser* - For any event-related lambda/APIs, the convention would be as follows: > 📢 **webd_event_eventName_functionName** Ex. **webd_event_christmas_sendGifts.** This lambda function is for sending gifts to users during some Christmas event hosted by MyWays. Here, since it is an event, it has an event, then eventName as Christmas, and then the API name. - For the functions that are triggered by other functions or are not solely responsible for generating responses to an API endpoint, the convention would be: > 📢**webd_trigger_triggeringFunction_functionName** For ex. **webd_trigger_register_sendVerificationCode.** Here, we have a trigger fu - For the **authorizers,** the convention would be: > 📢 **webd_authorizer_authorizerFor_functionName** For ex. **webd_authorizer_user_premiumUser.** Here, this is the authorizer for user to check if he is premium user or not. This authorizer can be put on the API gateway which consists of API for the premium user. ### How to name the function: 1. Generally, the function does one of the four things: 2. Create a new entity 3. Read an already created entity 4. Update an entity 5. Check for some conditions. For ex: is the user premium or not, has the user seen the popup or not, is the user registered for Bootcamp or not, etc. While naming the function, we can make sure that the function starts with the verb to make the function name self-descriptive. Convention for verbs are: - **create,** if a function creates a new entity. ```jsx const createUser = () => { // logic goes here } const createBootcampUser = () => { // logic goes here } const createPracticumUser = () => { // logic goes here } ``` - **get,** if a function reads the data. ```jsx const getUser = () => { // logic } const getMessageNotification = () => { // logic goes here } const getPremiumUsers = () => { // logic goes here } ``` - **update**, if the function updates an already created entity ```jsx const updateUser = () => { // logic goes here } const updateBlog = () => { // logic goes here } const updateProfile = () => { // logic goes here } ``` - **is**, if the function checks for some conditon. ```jsx const isUserPremium = () => { // logic goes here } const isBootcampUser = () => { // logic goes here } // There may be some case where "has" seems to be grammatically correct, // for ex: hasUserSeenTheNotification. // in such cases, we can change it to "isNotificationSeenByTheUser" const isNotificationSeenByTheUser = () => { // logic goes here } ``` ## Practices to follow when writing a Lambda Function: - **Write your codes in chunks:**  The best way to unit test your code is to write it with unit testing in mind. Try to keep your code in the main handler method to a minimum, only routing and calling other functions. This way you can test the other functions in isolation. - **Run local:** Serverless framework provides the [capability](https://serverless.com/framework/docs/providers/aws/cli-reference/invoke-local/) to run your function locally without needing to deploy it. Your code lives in your local machine while it emulates the AWS Lambda function environment for you. It is very helpful to have your data sample ready before you start coding. - **Use [environment variables](https://docs.aws.amazon.com/lambda/latest/dg/configuration-envvars.html)** to pass operational parameters to your function**.** # API GATEWAY Kebab case for gateways. # HTTP METHODS: We mostly use only **FOUR** types of methods: **GET, POST, PATCH, DELETE**. ## GET: - These requests should only be used for fetching. No manipulation/creation of data should be done on this request. - Data from the client should be sent using query parameters. - The naming convention for query parameters is **snake_case.** - If the doesn't change frequently, make sure to use Redis. ## POST: - These requests should be used for creating the data. - The data should be sent in the body. - The keys for the JSON data should be in **snake_case.** ## PATCH: - These request should be used whenever we are updating any exisiting document in the database. - The data should be in the body ## **DELETE:** - These request should be used when we are removing/deleting an existing document from the database. ### **NAMING CONVENTION FOR API ENDPOINTS:** > ✅ **No verbs should be present in the endpoint name and noun should be in the plural form** > 🚫 **An API endpoint cannot be name /getUser or /updateUser or /createUser** - For fetching data GET method should be used and API endpoint name should only reference to the model name. ✅ **GET /users** : This endpoint will return a list of all the users - For fetching based on specinc id or any other parameter. ✅ **GET /users/:id** : This endpoint should retrun user with the given id - For creating a new user, ✅ **POST /users** : This API should create a new user - For updating any information of existing user ✅ **PATCH /users/:id** This endpoint should update the info of user with the given id - For deleting any user ✅ **DELETE /users/:id** : This should delete the user with the given id. ### General Practices to follow: - Always make the UI first and note the exact data which is required. Then while designing the API, **only send the required data to the client**. This reduces the payload. - Always wrap the QUERYING/CREATING logic in **try-catch** block. - Use aggregations wherever possible. > ✅ **Use of **project** and **select** in mongoose for reducing payload and selecting required data.** ### Response type and Error codes: ### Convention for writing error messages: A good error message should be descriptive. It should mention whatever went wrong, why it went wrong and a key to fix it, if possible. **For example:** #### If in the function **updateUser,** the userId passed by the client doesn't exist. So, a lame error message would be: > ⛔ user_id does not exist. #### A more descriptive error message can be: > ✅ **User cannot be updated as a user with the userId 678393930gb2873y538 doesn't exist.** #### Always provide context with the error message. > ⛔ invalid format for the image. > ✅ **Invalid format for Image. txt/jpeg/png is expected but pdf is provided.** Try to be as descriptive with the error message as possible. This leads to a good time while debugging. > 📢 **For function which is interacting with AWS, always make sure to log the errors. This makes it easy for the DevOps team to resolve the error.** ### Response Format: - The response should always be in **JSON format.** - Structure of the response object should be: ```jsx { // If any message needs to be sent to the client. This can be empty but the key should // always be present. "message" : "" // Each response should be wrapped in "data". data: { key_name_1 : {}, key_name_2 : {}/ ... } } // In case of error: { "message" : error_message data: null } ``` - Status code should be used wisely. We are only using these status codes: - **200 Success** : This denotes that everything went well and the response has been successfully delivered to the client. - **400 Bad Requests**: This denotes that the client-side input has failed documentation/validation. - **401 Unauthorized:** This denotes that the user is unauthorized for accessing a resource. Usually, it returns when a user is not verified. - **403 Forbidden:** This denotes that the user is inappropriate and is not allowed to access a resource even after being verified. - **404 Not Found:** This denotes that no resources are found. - **500 Internal server error:** This is a common server error. # **DOCUMENTATION OF APIS** Documentation of each API is a must. API documentation should have: - endpoint - method - description - headers - body - query_parameters - request_parameter - response-structure - example-request - example-response ```jsx endpoint: /profile/:id method: GET description: returns the profile of the user with given id. headers: Auth header body: {} query_parameters: {} request_parameters: {"id"} reponse_structure: { message: "", data:{ user_id: name: roll_no: } } ``` > ✅ **INPUT VALIDATION** i**s done using JOI. Every param, which a lambda receives should be validated against JOI.** > ✅ **We can use Sentry for logging errors both at the front end and backend(lambdas).** ### Documentation of Lambda Functions: Lambda would be documented at the function level. This means any function inside the lambda should have its documentation above it. ### Example ``` /** name: mainFunction description: A function to return full name. parameters: firstName: String, lastName: String return: fullName: String */ function mainFunction(firstName, lastName) { const fullName = firstName + " " + lastName return fullName } ```

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully