aws-amplify / amplify-backend

Home to all tools related to Amplify's code-first DX (Gen 2) for building fullstack apps on AWS
Apache License 2.0
185 stars 62 forks source link

feat: Add lamda data client support #2224

Open stocaaro opened 1 week ago

stocaaro commented 1 week ago

Problem

Users would like to use the Gen2 data client interface to access their APIs from application functions (lambda's).

Our docs offer instructions on this experience, which stop short of indicating how the customer should provide the model introspection schema needed to make the whole experience work.

Changes

  1. Build the model introspection schema
    1. Build the Model Introspection Schema (MIS) in the data factory
    2. Construct an S3 bucket with the MIS as an object
    3. Grant get permission to the MIS to any function that is granted resource permissions to the data schema
    4. Add the bucket name and object key for the MIS to SSM (where it will be read
  2. Add config function for user ease
    1. Add a configuration function we can internally import from import { getAmplifyClientsConfiguration } from "@aws-amplify/backend/function/runtime";

Example: amplify/functions/todo-count/handler.ts

import type { Handler } from "aws-lambda";
import { Amplify } from "aws-amplify";
import { generateClient } from "aws-amplify/data";
import type { Schema } from "../../data/resource";

import { getAmplifyDataClientConfig } from "@aws-amplify/backend/function/runtime";
import { env } from "$amplify/env/todo-count";

const { resourceConfig, libraryOptions } = await getAmplifyDataClientConfig(env)
Amplify.configure(resourceConfig, libraryOptions);

const client = generateClient<Schema>();

export const handler: Handler = async () => {
  const todos = (await client.models.Todo.list()).data;
  return todos.length;
};

Corresponding docs PR, if applicable: https://github.com/aws-amplify/docs/pull/8096

Validation

Checklist

By submitting this pull request, I confirm that my contribution is made under the terms of the Apache 2.0 license.

changeset-bot[bot] commented 1 week ago

🦋 Changeset detected

Latest commit: 6e3ba6156c4d85dbfe832618f07e4997823dbfee

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 3 packages | Name | Type | | ----------------------------- | ----- | | @aws-amplify/backend | Minor | | @aws-amplify/backend-function | Minor | | @aws-amplify/backend-data | Patch |

Not sure what this means? Click here to learn what changesets are.

Click here if you're a maintainer who wants to add another changeset to this PR

stocaaro commented 6 days ago

re: E2E testing. I plan to merge this test PR onto this change once the MIS PR is merged.

I have appreciated having these 3 separate during review/prep to keep the PR size manageable, but if having them merged into one (here) at this time is better at this point, I can combine them.