Skip to content

Instantly share code, notes, and snippets.

@danibrear
Last active December 3, 2020 13:53
Show Gist options
  • Save danibrear/96b29a426ebbfd0ab643fbf1e78b36e9 to your computer and use it in GitHub Desktop.
Save danibrear/96b29a426ebbfd0ab643fbf1e78b36e9 to your computer and use it in GitHub Desktop.
Amplify Auth Field-Level Authorization Example
// From https://docs.amplify.aws/cli/graphql-transformer/auth#field-level-authorization
// The code where this exception is thrown is: https://github.com/aws-amplify/amplify-js/blob/d9aa32837f15f408daba0a0104bb27042b9331da/packages/api-graphql/src/GraphQLAPI.ts#L314
type User @model {
id: ID!
username: String
ssn: String @auth(rules: [{ allow: owner, ownerField: "username" }])
}
// Amplify will automatically generate the query
const getUser = /* GraphQL */ `
query GetUser($id: ID!) {
getUser(id: $id) {
id
username
ssn
}
}
`;
// I'd use this in this way for async requests
import API, { graphqlOperation, GraphQLResult } from "@aws-amplify/api";
const getUserById = async (userId: string): Promise<User | null> => {
try {
const response = await API.graphql(graphqlOperation(getUser, { id: userId}));
/** HERE response SHOULD be structured like this:
{
data: { getUser: {id, username, ssn} }
}
Where SSN would be null if you are not the owner.
*/
return e.data.getUser;
} catch (err) {
/** Here I would assume there was an error with the query...
HOWEVER with the auth rule, there is an exception thrown even though the
data is correct. so I have to do this...*/
if (err.data && err.data.getUser) {
return err.data.getUser;
}
console.log('Error getting the user: ', err);
return null;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment