When creating Lightning Web Components, how often have you had to create an Apex class just to do a simple query. Even for the simplest of queries, you’ve to create 2 Apex classes, one class that does the query and one additional test class. And often, you want to avoid this overhead for simpler use-cases.
Concept: Reusable Modules
If you’re new to the LWC world, think of “reusable module” as helper/utility class in Apex.
How does it work?
I’ve created a (utility) Lightning Web Component that you can install as a package and use in your Lightning Web Components directly and query data using from database. You can check out the source code in this repo.
The repo also contains a README file that has the package link, “How to use” code snippets and some more details about the query behavior.
- Running Queries with System Mode is a security concern so be careful with that.
- Referencing fields in query strings would require adding the fields as references (as import statements) to the LWCs to maintain Metadata Integrity (i.e. deleting a field which is used only in LWC queries).
- Also, make sure your code is handling SOQL injection.
Hope you find this one useful! Catch you in the next one! ✌️
And thank you for being an awesome reader! Subscribe to this blog for receiving all the latest updates straight to your inbox. 🙂
2 thoughts on “LWC SOQL Utility – One Apex class for all queries”
hey just curious – why would you chose to do this over the new GraphQL API?
I wouldn’t. It’s just that GraphQL is only via a pilot program for LWC, so there’s not telling when it will be GA. 🙂