Giter Club home page Giter Club logo

block-content-with-sdk-ef-integration's Introduction

image

Block content based on the user's location using the Netlify SDK

This integration is created using the Netlify SDK. It injects an edge function into the user's site that checks the user's location and blocks the content if they are in a specific country.

Adding an Integration UI

While it's possible for the user of this integration to set BLOCKED_COUNTRY_CODE as an environment variable manually, we want to provide them with a UI to easily set this value. To do this, we'll use the Integration UI. In this section we'll explain how we set it up in this example.

Creating API Handlers

Inside of the src/index.ts file we've added two API handlers with integration.addApiHandler. One of these sets the BLOCKED_COUNTRY_CODE environment variable and the other gets the current value of BLOCKED_COUNTRY_CODE.

integration.addApiHandler(
  'save-blocked-country-code',
  async ({ body }, { client, siteId, teamId }) => {
    try {
      if (!body || !siteId || !teamId) {
        return {
          statusCode: 400,
          body: 'Bad request: Missing required parameters',
        };
      }

      const { BLOCKED_COUNTRY_CODE } = JSON.parse(body);
      if (!BLOCKED_COUNTRY_CODE) {
        return {
          statusCode: 400,
          body: 'Bad request: Missing BLOCKED_COUNTRY_CODE in body',
        };
      }

      // This uses the Netlify SDK to create or update the BLOCKED_COUNTRY_CODE environment variable
      await client.createOrUpdateVariable({
        accountId: teamId,
        siteId,
        key: 'BLOCKED_COUNTRY_CODE',
        value: BLOCKED_COUNTRY_CODE,
      });

      return {
        statusCode: 200,
        body: 'Variable successfully created or updated',
      };
    } catch (error) {
      let errorMessage = 'Something went wrong';

      if (error instanceof Error) {
        errorMessage = error.message;
      }

      return {
        statusCode: 500,
        body: errorMessage,
      };
    }
  }
);

integration.addApiHandler(
  'get-blocked-country-code',
  async ({ body }, { client, siteId, teamId }) => {
    try {
      if (!siteId || !teamId) {
        return {
          statusCode: 400,
          body: 'Bad request: Missing required parameters',
        };
      }

      // This uses the Netlify SDK to get the BLOCKED_COUNTRY_CODE environment variable
      const envVars = await client.getEnvironmentVariables({
        accountId: teamId,
        siteId,
      });

      const BLOCKED_COUNTRY_CODE = envVars.find(
        (envVar) => envVar.key === 'BLOCKED_COUNTRY_CODE'
      )?.values[0].value;

      if (!BLOCKED_COUNTRY_CODE) {
        return {
          statusCode: 404,
          body: 'BLOCKED_COUNTRY_CODE not found',
        };
      }

      return {
        body: JSON.stringify({
          BLOCKED_COUNTRY_CODE,
        }),
        statusCode: 200,
      };
    } catch (error) {
      let errorMessage = 'Something went wrong';

      if (error instanceof Error) {
        errorMessage = error.message;
      }

      return {
        statusCode: 500,
        body: errorMessage,
      };
    }
  }
);

Creating the UI

We've created a simple UI that allows the user to set the BLOCKED_COUNTRY_CODE environment variable. You can find this UI inside of src/ui/index.ts. In this file we define the Integration UI.

import { NetlifyIntegrationUI } from '@netlify/sdk';

const integrationUI = new NetlifyIntegrationUI('ABC Integration');
const surface = integrationUI.addSurface('integrations-settings');
const route = surface.addRoute('/');

export { integrationUI };

We then use the route.onLoad method to get the current value of BLOCKED_COUNTRY_CODE by doing a fetch to our previously defined get-blocked-country-code API Handler and set it as the value of the input field that we'll create next.

route.onLoad(async (surfaceState) => {
  const { picker, fetch } = surfaceState;

  const response = await fetch('get-blocked-country-code', {
    method: 'GET',
  });

  const { BLOCKED_COUNTRY_CODE } = await response.json();

  picker.setFormInputValue(
    'configuration-form',
    'BLOCKED_COUNTRY_CODE',
    BLOCKED_COUNTRY_CODE
  );
});

Now we'll add a form to our route that allows the user to set the BLOCKED_COUNTRY_CODE environment variable. We'll use the route.addForm method to do this.

route.addForm(
  {
    title: 'Configuration',
    id: 'configuration-form',
    onSubmit: async (surfaceState) => {
      const { picker, fetch } = surfaceState;

      const BLOCKED_COUNTRY_CODE = picker.getFormInputValue(
        'configuration-form',
        'BLOCKED_COUNTRY_CODE'
      );

      await fetch('save-blocked-country-code', {
        method: 'POST',
        body: JSON.stringify({
          BLOCKED_COUNTRY_CODE,
        }),
      });
    },
  },
  (card) => {
    card.addInputSelect({
      id: 'BLOCKED_COUNTRY_CODE',
      label: 'Blocked Country Code',
      options: myCountryCodes,
    });
  }
);

As you can see we call the save-blocked-country-code API Handler and pass the BLOCKED_COUNTRY_CODE value as the body of the request when the user submits the form.

For ease of use, we've used a library to get a list of country codes. This is the logic that creates the list myCountryCodes that we pass to the options property of the card.addInputSelect method:

import countryCodes from 'country-codes-list';

const myCountryCodes = Object.entries(
  countryCodes.customList('countryCode', '{countryNameEn}')
).map(([value, label]) => ({
  value,
  label,
}));

block-content-with-sdk-ef-integration's People

Contributors

khendrikse avatar

Watchers

Mathias Biilmann avatar Chad Eubanks avatar Patrick D'appollonio avatar Bob McDonough avatar Kaya W avatar RJ Beers avatar Penny John avatar James McNeil avatar  avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.