Skip to content

Commit 0dfff00

Browse files
stocaarojosefaidt
andauthored
feat: Fix examples to use lambda data client (#8096)
* feat: Fix examples to use lambda data client * fix: Schema import pattern * Update src/pages/[platform]/build-a-backend/data/customize-authz/grant-lambda-function-access-to-api/index.mdx Co-authored-by: josef <[email protected]> * Add warning after data client handler examples * Update src/pages/[platform]/build-a-backend/data/customize-authz/grant-lambda-function-access-to-api/index.mdx Co-authored-by: josef <[email protected]> * Update src/pages/[platform]/build-a-backend/data/customize-authz/grant-lambda-function-access-to-api/index.mdx Co-authored-by: josef <[email protected]> * Update src/pages/[platform]/build-a-backend/data/customize-authz/grant-lambda-function-access-to-api/index.mdx Co-authored-by: josef <[email protected]> * Apply suggestions from code review Co-authored-by: josef <[email protected]> --------- Co-authored-by: josef <[email protected]>
1 parent b362e1b commit 0dfff00

File tree

2 files changed

+47
-121
lines changed
  • src/pages/[platform]/build-a-backend
    • data/customize-authz/grant-lambda-function-access-to-api
    • functions/examples/create-user-profile-record

2 files changed

+47
-121
lines changed

src/pages/[platform]/build-a-backend/data/customize-authz/grant-lambda-function-access-to-api/index.mdx

Lines changed: 34 additions & 71 deletions
Original file line numberDiff line numberDiff line change
@@ -35,19 +35,16 @@ Function access to `defineData` can be configured using an authorization rule on
3535
import {
3636
a,
3737
defineData,
38-
defineFunction,
3938
type ClientSchema
4039
} from '@aws-amplify/backend';
41-
42-
const functionWithDataAccess = defineFunction({
43-
entry: '../functions/data-access.ts'
44-
});
40+
import { functionWithDataAccess } from '../function/data-access/resource';
4541

4642
const schema = a
4743
.schema({
4844
Todo: a.model({
4945
name: a.string(),
50-
description: a.string()
46+
description: a.string(),
47+
isDone: a.boolean()
5148
})
5249
})
5350
// highlight-next-line
@@ -60,14 +57,25 @@ export const data = defineData({
6057
});
6158
```
6259

60+
Create a new directory and a resource file, `amplify/functions/data-access/resource.ts`. Then, define the Function with `defineFunction`:
61+
62+
```ts title="amplify/functions/data-access/resource.ts"
63+
import { defineFunction } from '@aws-amplify/backend';
64+
65+
export const functionWithDataAccess = defineFunction({
66+
name: 'data-access',
67+
});
68+
```
69+
6370
The object returned from `defineFunction` can be passed directly to `allow.resource()` in the schema authorization rules. This will grant the function the ability to execute Query, Mutation, and Subscription operations against the GraphQL API. Use the `.to()` method to narrow down access to one or more operations.
6471

65-
```ts
72+
```ts title="amplify/data/resource.ts"
6673
const schema = a
6774
.schema({
6875
Todo: a.model({
6976
name: a.string(),
70-
description: a.string()
77+
description: a.string(),
78+
isDone: a.boolean()
7179
})
7280
})
7381
// highlight-start
@@ -77,8 +85,6 @@ const schema = a
7785
// highlight-end
7886
```
7987

80-
When configuring function access, the function will be provided the API endpoint as an environment variable named `<defineDataName>_GRAPHQL_ENDPOINT`, where `defineDataName` is transformed to SCREAMING_SNAKE_CASE. The default name is `AMPLIFY_DATA_GRAPHQL_ENDPOINT` unless you have specified a different name in `defineData`.
81-
8288
<Callout info>
8389

8490
Function access can only be configured on the schema object. It cannot be configured on individual models or fields.
@@ -89,86 +95,43 @@ Function access can only be configured on the schema object. It cannot be config
8995

9096
In the handler file for your function, configure the Amplify data client
9197

92-
```ts title="amplify/functions/data-access.ts"
98+
```ts title="amplify/functions/data-access/handler.ts"
99+
import type { Handler } from 'aws-lambda';
100+
import type { Schema } from '../../data/resource';
93101
import { Amplify } from 'aws-amplify';
94102
import { generateClient } from 'aws-amplify/data';
95-
import { Schema } from '../data/resource';
103+
import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtime';
96104
import { env } from '$amplify/env/<function-name>'; // replace with your function name
97105

106+
const { resourceConfig, libraryOptions } = await getAmplifyDataClientConfig(env);
98107

99-
Amplify.configure(
100-
{
101-
API: {
102-
GraphQL: {
103-
endpoint: env.<amplifyData>_GRAPHQL_ENDPOINT, // replace with your defineData name
104-
region: env.AWS_REGION,
105-
defaultAuthMode: 'identityPool'
106-
}
107-
}
108-
},
109-
{
110-
Auth: {
111-
credentialsProvider: {
112-
getCredentialsAndIdentityId: async () => ({
113-
credentials: {
114-
accessKeyId: env.AWS_ACCESS_KEY_ID,
115-
secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
116-
sessionToken: env.AWS_SESSION_TOKEN,
117-
},
118-
}),
119-
clearCredentialsAndIdentityId: () => {
120-
/* noop */
121-
},
122-
},
123-
},
124-
}
125-
);
126-
127-
const dataClient = generateClient<Schema>();
108+
Amplify.configure(resourceConfig, libraryOptions);
109+
110+
const client = generateClient<Schema>();
128111

129112
export const handler = async (event) => {
130113
// your function code goes here
131114
}
132115
```
133116

134-
Use the command below to generate GraphQL client code to call your data backend.
135-
<Callout info>
136-
137-
**Note**: We are working on bringing the end-to-end typed experience to connect to your data from within function resources without needing this step. If you'd like to provide feedback the experience or have early access, join our [Discord community](https://discord.gg/amplify).
138-
139-
</Callout>
140-
141-
```sh title="Terminal" showLineNumbers={false}
142-
npx ampx generate graphql-client-code --out <path-function-handler-dir>/graphql
143-
```
144-
145-
146117
<Callout warning>
147-
148-
**Note:** Whenever you update your data model, you will need to run the command above again.
149-
118+
When configuring Amplify with `getAmplifyDataClientConfig`, your function consumes schema information from an S3 bucket created during backend deployment with grants for the access your function need to use it. Any changes to this bucket outside of backend deployment may break your function.
150119
</Callout>
151120

152121
Once you have generated the client code, update the function to access the data. The following code creates a todo and then lists all todos.
153122

154123
```ts title="amplify/functions/data-access.ts"
155124
const client = generateClient<Schema>();
156125

157-
export const handler = async (event) => {
158-
await client.graphql({
159-
query: createTodo,
160-
variables: {
161-
input: {
162-
name: "My first todo",
163-
description: "This is my first todo",
164-
},
165-
},
166-
});
167-
168-
169-
await client.graphql({
170-
query: listTodos,
171-
});
126+
export const handler: Handler = async (event) => {
127+
const { errors: createErrors, data: newTodo } = await client.models.Todo.create({
128+
name: "My new todo",
129+
description: "Todo description",
130+
isDone: false,
131+
})
132+
133+
134+
const { errors: listErrors, data: todos } = await client.models.Todo.list();
172135

173136
return event;
174137
};

src/pages/[platform]/build-a-backend/functions/examples/create-user-profile-record/index.mdx

Lines changed: 13 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -92,75 +92,38 @@ export const postConfirmation = defineFunction({
9292
});
9393
```
9494

95-
Run the command `npx ampx sandbox` to create the backend, then use the command below to generate GraphQL client code to call your data backend.
96-
<Callout info>
97-
98-
**Note**: We are working on bringing the end-to-end typed experience to connect to your data from within function resources without needing this step. If you'd like to provide feedback on the experience or want to have early access, join our [Discord community](https://discord.gg/amplify).
99-
100-
</Callout>
101-
102-
```sh title="Terminal" showLineNumbers={false}
103-
npx ampx generate graphql-client-code --out <path-to-post-confirmation-handler-dir>/graphql
104-
```
105-
10695
Then, create the corresponding handler file, `amplify/auth/post-confirmation/handler.ts`, file with the following contents:
10796

10897
```ts title="amplify/auth/post-confirmation/handler.ts"
10998
import type { PostConfirmationTriggerHandler } from "aws-lambda";
11099
import { type Schema } from "../../data/resource";
111100
import { Amplify } from "aws-amplify";
112101
import { generateClient } from "aws-amplify/data";
102+
import { getAmplifyDataClientConfig } from '@aws-amplify/backend/function/runtime';
113103
import { env } from "$amplify/env/post-confirmation";
114-
import { createUserProfile } from "./graphql/mutations";
115-
116-
Amplify.configure(
117-
{
118-
API: {
119-
GraphQL: {
120-
endpoint: env.AMPLIFY_DATA_GRAPHQL_ENDPOINT,
121-
region: env.AWS_REGION,
122-
defaultAuthMode: "iam",
123-
},
124-
},
125-
},
126-
{
127-
Auth: {
128-
credentialsProvider: {
129-
getCredentialsAndIdentityId: async () => ({
130-
credentials: {
131-
accessKeyId: env.AWS_ACCESS_KEY_ID,
132-
secretAccessKey: env.AWS_SECRET_ACCESS_KEY,
133-
sessionToken: env.AWS_SESSION_TOKEN,
134-
},
135-
}),
136-
clearCredentialsAndIdentityId: () => {
137-
/* noop */
138-
},
139-
},
140-
},
141-
}
104+
105+
const { resourceConfig, libraryOptions } = await getAmplifyDataClientConfig(
106+
env
142107
);
143108

144-
const client = generateClient<Schema>({
145-
authMode: "iam",
146-
});
109+
Amplify.configure(resourceConfig, libraryOptions);
110+
111+
const client = generateClient<Schema>();
147112

148113
export const handler: PostConfirmationTriggerHandler = async (event) => {
149-
await client.graphql({
150-
query: createUserProfile,
151-
variables: {
152-
input: {
153-
email: event.request.userAttributes.email,
154-
profileOwner: `${event.request.userAttributes.sub}::${event.userName}`,
155-
},
156-
},
114+
await client.models.UserProfile.create({
115+
email: event.request.userAttributes.email,
116+
profileOwner: `${event.request.userAttributes.sub}::${event.userName}`,
157117
});
158118

159119
return event;
160120
};
161121

162122
```
163123

124+
<Callout warning>
125+
When configuring Amplify with `getAmplifyDataClientConfig`, your function consumes schema information from an S3 bucket created during backend deployment with grants for the access your function need to use it. Any changes to this bucket outside of backend deployment may break your function.
126+
</Callout>
164127

165128

166129
Lastly, set the newly created Function resource on your auth resource:

0 commit comments

Comments
 (0)