aws amplify graphql computed field inline resolver - graphql

For complex field resolver, I know #function directive is the way to go.
But how about those very simple computed fields. #function directive with lambda is a little too much. I see prisma has inline javascript function supported. see the answer of similar quest.
Not sure whether aws-amplify graphql support inline function.

You can override the default VTL resolver for the field, just adding the logic you want.
This article goes into detail on a simple use case (similar to yours I think)
Just a few steps
Add the field to your schema
Build your API
Look for the auto-generated resolver (amplify/backend/api/client/build/resolvers) The naming convention is straight-forward.
Copy it to amplify/backend/api/client/resolvers
Change it as needed
Push your changes to Amplify
In the article he has just added a new set item
## [Start] Prepare DynamoDB PutItem Request. **
$util.qr($context.args.input.put("createdAt", $util.time.nowISO8601()))
$util.qr($context.args.input.put("updatedAt", $util.time.nowISO8601()))
# The next line was added
$util.qr($context.args.input.put("active", false))
AWS has some tutorials over VTL that you might want to take a look.
And Amplify has more docs on custom resolvers using VTL

Related

Authorize based on field value in another document in AppSync GraphQL custom authentication via Lambda Resolver

I am new to Amplify Datastore & AppSync w/ GraphQL, but in Firestore, you can write an auth rule like: allow delete: if request.auth != null && get(/databases/$(database)/documents/users/$(request.auth.uid)).data.admin == true [https://firebase.google.com/docs/firestore/security/rules-conditions#access_other_documents] -> which would grab the document at /users/{id}/ and I can access the admin field to write a security rule logic.
How do you do the same in a Lambda function resolver?
I am aware that the solution may involve a Lambda resolver (https://stackoverflow.com/a/68581796/9824103) but I cannot find any reference to reading a specific document and doing logic to authorize or deny an operation based on a field value in a document. I am only asking how to do this specific thing. Thank you!
I followed https://docs.amplify.aws/cli/graphql/authorization-rules/#custom-authorization-rule to create a custom authorization rule via adding the #rule directive: type MyModel #model #auth(rules: [{ allow: custom }]) and.. although the lambda function isn't really getting called when I try to write a listMyModel or createMyModel (any hints as to why that would be great), I am focused on writing the lambda function to read query a document and check a certain field to meet my custom auth condition.
fyi, I am using Flutter based amplify-cli.

How to modify headers to RTK Query set by prepareHeaders when code splitting?

Using RTK Query code generation I have a generated slice of my API from an OpenAPI spec. Following on from that example I have extended the generated slice as described by using generatedApi.enhanceEndpoints({/**/}).
Now I want to add prepareHeaders to the slice which is typically set via fetchBaseQuery, and per the docs my use case is for adding an auth token to each request. As the createApi function is called within the generated file I'd like to avoid touching this to include custom logic.
I think I'm looking for something like generatedApi.enhancePrepareHeaders({/**/}) which does not seem to exist yet.
How do I set headers for all requests when following the code splitting approach and without touching the generated file?
At the moment, that is only possible by writing a custom baseQuery function wrapping the original fetchBaseQuery.
From the next version of the code generator on, it will only create injectEndpoints calls and leave all the baseQuery configuration to a non-generated file.

Is it possible to map a subscription parameter to an array at the mutation output?

I have a theoretical question. As I know subscription parameters must exist as a field in the returning type of the mutation. This means that the type of parameter must also match the type of the field in the returning object of the mutation. Am I right? Suppose I get an array with channels ids in the mutation response. I only send one channel id as a parameter in the subscription. Is it possible to map a subscription parameter to an array at the mutation output? If the channel id exists in the array (field channelsIds), the subscription must work. Is it possible to write this logic in the scheme itself, or is it technically impossible?
GraphQL schema:
schema {
mutation: Mutation
subscription: Subscription
}
type Mutation {
testMutation(input: TestMutationInput): TestMutationOutput
}
type TestMutationOutput {
channelsIds: [String!]!
userId: String!
userEmail: String
userPhoneNumber: String
}
type Subscription {
watchTestMutation(channelId: String!): TestMutationOutput
#aws_subscribe(mutations: ["testMutation"])
}
If I understand you correctly you want to filter based on if the mutation's returned value is in an array that is passed as an argument to the subscription. Sorry to say that is not possible at this time. Subscription filters only evaluate to true or false and cannot accommodate any logic other than that.
At the end of October 2020, I contacted AWS support for advice on this issue. I think this answer may be useful to someone, so I post their answer.
Please allow me to inform you that the use-case that you have
mentioned in the case is currently not possible via AppSync. I
understand that the lack of the feature may be causing inconvenience.
There is an internal feature request already with the AppSync team to
incorporate this feature and I have added a +1 on your behalf. It is
worth noting, that once this feature request is with the team, it will
be up to the team as to if/when this potential infrastructure feature
is implemented, and because of the limited visibility into the
progress of internal development processes, I won’t be able to provide
an ETA regarding its release. I would request you to keep an eye on
the what's new page or the AWS Blogs as all new feature requests and
enhancements are posted there[1-3].
However we can suggest a couple of workarounds in this case:
Filter the required fields on client side itself after receiving the values on the client-side from AppSync.
If the values to be filtered are very limited we can use a fake mutation made with the help of a resolver mapped to “None” Data
source. In this flow, we would create a lambda function that uses a
DynamoDB stream as the trigger. The Lambda function is triggered
whenever there's an update to the DynamoDB table.

We can then include logic in the Lambda function to filter the
required fields and perform a mutation to AppSync. In AppSync, the
mutation which was called by lambda would configured using a resolver
mapped to a “None” Data source. The None data source type passes the
request mapping template directly to the response mapping template.
And when we subscribe to this mutation, we will directly get the
filtered data from Lambda that was used to call this mutation. Please
refer to [4] for a step-by-step description of this process.
But please note that this workaround is cumbersome and would require a lot of changes if the required field values keep changing. Workaround 1(handling it on the client-side) is usually the preferred way to handle this use-case.
Resources:
[1] https://blogs.amazon.com/
[2] https://aws.amazon.com/new/
[3] https://aws.amazon.com/releasenotes/
[4] https://aws.amazon.com/premiumsupport/knowledge-center/appsync-notify-subscribers-real-time/

Accessing Cognito Custom Attributes in a post-confirmation lambda function

I have a post-confirmation lambda function that writes user attribute information to a dynamoDB table. I've managed to get access to standard user attributes fields in the "event" parameter by doing stuff like
event.request.userAttributes.sub
but trying to run
event.request.userAttributes.role //where role is the name of my custom attribute
doesn't seem to work. Anyone know what the proper syntax for this is? And do I need to set any special read permissions for custom attributes? I created this custom attribute a long time after I originally made this user pool, if that changes things.
All custom attributes are prefixed with the custom: prefix (Documentation - Custom Attributes).
Therefore (I'll assume you're using JavaScript here- if not feel free to specify and I can change this example), you'd need to use:
event.request.userAttributes['custom:role']
You don't need to set any special read permissions- all the user attributes are returned in the PostConfirmation lambda.

How can I use isValidJSValue to validate a query variable in my client code?

I'm writing client-side code for an app that will query a GraphQL server. In a couple of places in my code, I'm passing around data that will eventually get turned into a query variable, so it needs to validate against a specific GraphQLInputType in my schema. On looking into some of the utilities that graphql-js provides, it looks like the isValidJSValue checker is exactly what I'm looking for, and its comments even mention that it's intended to be used to do just that.
The issue is that I don't have access to the GraphQL type I want to validate against as a JS object, which is what I'm pretty sure that function is looking for. I'm importing my schema (as an npm depdendency) as JSON, or I also have it in the schema notation. Is there some other utility I can use to get the JS type I need from one of those sources, and then use that to check my data with isValidJSValue? Or is there some other way I could go about this that I just haven't thought of?
You can use the JSON schema you have imported to construct an actual GraphQL schema instance using buildClientSchema here: https://github.com/graphql/graphql-js/blob/master/src/utilities/buildClientSchema.js
Then, it should be a simple matter of looking in the types field of the resulting schema to find your input type, and then calling isValidJSValue on it.
I'm curious, though - why validate the value on the client before sending it, rather than just relying on the validation the server will do?

Resources