Yan Cui
I help clients go faster for less using serverless technologies.
This article is brought to you by
Don’t reinvent the patterns. Catalyst gives you consistent APIs for messaging, data, and workflow with key microservice patterns like circuit-breakers and retries for free.
I had been working on a client project where I built the GraphQL backend for a new social network using primarily AppSync, Lambda and DynamoDB.
One of the features of the app was to support private messaging between two users. To allow either user to fetch their chat messages in chronological descending order, I modelled the chat_messages DynamoDB table as below:
where userIds
is the HASH key, and timestamp is the RANGE
key.
Here, userIds
is a composite key made up of the two users’ IDs, arrange in lexicographical order. If you know the two users’ IDs, you can fetch the chat messages using a DynamoDB Query
operation.
So in the VTL template, I had something like this:
However, this didn’t work.
Given the following input:
The $userIds
variable would be interpreted as 35c1f714–46c1–4ccb-87fc-933da626ce6a_08371580–48e2–43e7–9b1c-75804b9e7e12
, where the user IDs are arranged in the wrong order. What’s going on?
If you work with Java everyday then the problem might be obvious to you, that to compare strings lexicographically you need to use the compareTo
method on the first string. And since VTL is implemented in Java, that is also the case here.
Instead, the right way to do it is this:
I have found the VTL Reference page very handy while working with VTL. But unfortunately, lexicographical string comparison was not mentioned in the VTL docs. Without helpful folks like Richard and Franck I would have easily spent hours banging my head against this problem!
— Richard H. Boyd (@rchrdbyd) April 27, 2020
Maybe?
— Franck (@Franck_chester) April 27, 2020
I hope this post helps you in a similar way should you run into the same problem, as my way of passing it forward.
Whenever you’re ready, here are 3 ways I can help you:
- Production-Ready Serverless: Join 20+ AWS Heroes & Community Builders and 1000+ other students in levelling up your serverless game. This is your one-stop shop for quickly levelling up your serverless skills.
- I help clients launch product ideas, improve their development processes and upskill their teams. If you’d like to work together, then let’s get in touch.
- Join my community on Discord, ask questions, and join the discussion on all things AWS and Serverless.