Tutorial: Using Sqids encoding

From RAD Studio
Jump to: navigation, search

Go Up to Database and LiveBindings Tutorials


This tutorial shows how to use Sqids encoding in RAD Studio. Sqids is a handy feature when navigating a data structure like a database table.

RAD Server, by default, exposes URLs that might include specific internal information about the records. For instance, it is expected to identify an individual record using the primary key, often an ID. Therefore, servers might have endpoints with an ending similar to this /customer/12345.

There are multiple reasons why this is far from ideal, from the fact that you are sharing internal details (which might not be as neutral as a number) to the potential security implications of revealing a record ID.

There are many solutions to this problem, mainly around a bidirectional mapping of the record ID to a string. Rather than implementing a custom solution, starting with RAD Studio 12.0, we are adopting the Sqids library.

What is Sqids?

It is an open-source library that generates short IDs from positive numbers (for example, using the Sqids default settings, 12345 is encoded to A6da).

Moreover, Sqids allows the encoding of one or more positive numbers into a single ID. There is no limit on the amount of numbers to encode, but there is a limit on their length (depending on the implementation language).

To learn more about Sqids, visit Sqids FAQ.

Code Example: How to use Sqids encoding

To implement Sqids, RAD Studio 12.0 introduced a new class named System.NetEncoding.Sqids.TSqidsEncoding, which provides all the methods to use Sqids. The steps to implement it are:

  1. Make sure the System.NetEncoding.Sqids unit is under the uses clause.
  2. Create the TSqidsEncoding instance using the Create method.
  3. Encode the ID or IDs using the Encode method.
  4. Decode it using one of the following methods, depending on your application needs:
  5. You can destroy the TSqidsEncoding instance using the Destroy method.

Make a request to a web server using Sqids

There are two ways to make a request to a web server using Sqids:

In the second case, when it is time to send a request whose paramenter name starts with #, TRESTClient automatically creates an instance of TSqidsEncoding using TRESTClient.SqidsAlphabet and TRESTClient.SqidsMinLength properties.

On the other hand, in a RAD Server resource, when the ResourceSuffix parameter name starts with #, the value will be Sqids decoded. The algorithm's configuration is based on the EMSServer.ini file, particularly, Alphabet and MinHashLength parameters:

[Server.Sqids]
;# The following options control URL parameters Sqids decoding
;#
;# Optional alphabet for Sqids decoding
Alphabet=
;# Optional minimal hash length for Sqids decoding
MinHashLength=0
Note: To learn how to edit the EMSServer.ini file, please visit Editing the Configuration of Your RAD Server Engine Manually.

See Also