#✅ - Access Amplify Data from a LAMBDA ?

33 messages · Page 1 of 1 (latest)

bronze tiger
#

Hey! I'm trying to access AND update data from a LAMBDA function

import type { Schema } from "../../data/resource"
import { generateClient } from "aws-amplify/data";
import { Amplify } from "aws-amplify";
import { type AppSyncIdentityCognito } from 'aws-lambda';
import outputs from '../../../amplify_outputs.json';

Amplify.configure(
  outputs
);
const client = generateClient<Schema>({
  authMode: "iam",
});

export const handler: Schema["acceptOffers"]["functionHandler"] = async (event) => {
  const { id } = event.arguments;
  console.log((await client.models.Message.get({id: id as string})).errors);

  const message = (await client.models.Message.get({id: id as string})).data;

  if(!message) return false;
  
  if(message.recipientId === (event.identity as AppSyncIdentityCognito).username)
  {
    await client.models.Message.update({id: id as string, offerAccepted: true});
    return true;
  }
  return false;
};

Gives me the following error:
UnauthorizedException: Unknown error
recoverySuggestion: If you're calling an Amplify-generated API, make sure to set the "authMode" in generateClient({ authMode: '...' }) to the backend authorization rule's auth provider ('apiKey', 'userPool', 'iam', 'oidc', 'lambda')

And at the end of my data schema declaration (a.schema...), i've added .authorization((allow) => [allow.resource(acceptOffers)]) already

Is there maybe something i'm missing?

thorny sierra
#

maybe Amplify.configure should same as the document mentioned, not use outputs file like that

bronze tiger
#

and yes i've tried calling Amplify.configure like the document you mention, but the result is identical

#

but it seems they are using the .graphql api with the createTodo mutation, but i'm trying to get the .data to work

thorny sierra
#

these are my config, and it works well

bronze tiger
#

or where you import it from?

thorny sierra
#

try to run this command

#

npx ampx generate graphql-client-code --out <path-function-handler-dir>/graphql

#

it will generate the graphql folder as gen1

bronze tiger
#

done! except the error is still happening :/

#
import { updateConsultantProfile } from './graphql/mutations'
import { getMessage } from './graphql/queries'

export const handler: Schema["acceptOffers"]["functionHandler"] = async (event) => {
  const { id } = event.arguments;

  try{
    const response = await client.graphql({
      query: getMessage,
      variables: {
        id: id as string,
      },
    });
    console.log('Messages:', response);
  }catch(e){
    console.error('nierror: ', e);
  }
}```
thorny sierra
#

generateClient<Schema>({ authMode: "iam" }) your error mentioned this one? did you config it correct?

bronze tiger
#

yep!

const client = generateClient<Schema>({
  authMode: "iam",
});```

with the `authorization((allow) => [allow.resource(acceptOffers)]);` at the end of my schema definition
thorny sierra
#

with your error, it seem like there is some mistake in config we didn't notice ? 🤔

bronze tiger
#

problem fixed! it seems the issue was { authMode: "iam", } !

#

removing it, and simply using const client = generateClient<Schema>(); seems to be working! thanks for the help 😄

thorny sierra
#

authMode is based on what Authmode you config in Amplify.configure

#

in my case because i setup like this

bronze tiger
#

forgot to mention, i did modify the amplify.configure and that probably actually probably was the fix*

Amplify.configure(
  {
    API: {
      GraphQL: {
        endpoint: process.env.AMPLIFY_DATA_GRAPHQL_ENDPOINT as string,
        region: process.env.AWS_REGION,
        defaultAuthMode: "iam",
      },
    },
  },
  {
    Auth: {
      credentialsProvider: {
        getCredentialsAndIdentityId: async () => ({
          credentials: {
            accessKeyId: process.env.AWS_ACCESS_KEY_ID as string,
            secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string,
            sessionToken: process.env.AWS_SESSION_TOKEN as string,
          },
        }),
        clearCredentialsAndIdentityId: () => {
        },
      },
    },
  }
);```
narrow lionBOT
#

✅ - Access Amplify Data from a LAMBDA ?

#

Marked as solved.

#

Answer selected!

```javascript
Amplify.configure(
  {
    API: {
      GraphQL: {
        endpoint: process.env.AMPLIFY_DATA_GRAPHQL_ENDPOINT as string,
        region: process.env.AWS_REGION,
        defaultAuthMode: "iam",
      },
    },
  },
  {
    Auth: {
      credentialsProvider: {
        getCredentialsAndIdentityId: async () => ({
          credentials: {
            accessKeyId: process.env.AWS_ACCESS_KEY_ID as string,
            secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY as string,
            sessionToken: process.env.AWS_SESSION_TOKEN as string,
          },
        }),
        clearCredentialsAndIdentityId: () => {
        },
      },
    },
  }
);``````
Kudos to @bronze tiger!
#1280997860036575242 message
bronze tiger
#

Also, i was wondering, is it possible to speed up the graphql queries in my lambda function?

#

Because i have 5 graphql queries (they all return one or two elements only), but the lambda takes a whole 1100ms to execute (not only on cold start, but constantly! and cold start is 3000ms)

rapid quest
#

I'm not sure why it's taking that long, could be size of the bundle, other fetch requests if any besides the graphql query, etc.

If your lambda is only performing a gql query/mutation, then you could probably use an AppSync JS resolver instead. They don't have cold starts and are typically faster than lambda

bronze tiger
#

i doubt that would be feasible in an appsync resolver