Counters in Docly

Sometimes we need counters in our APIs to provide sequential numbers for our data, such as row IDs, ticket numbers, or customer numbers. This post explores how to use number series and counters effectively in your projects.

Why and What

Number series are like automatic counters. They help us keep track of things by giving them unique numbers. For example, when you need a new customer number or ticket ID, a counter can provide the next available number. This makes organizing and finding information much easier in our APIs and databases.

Incrementing and Retrieving Counter Value

To increment a counter and retrieve its new value from our API code, you can use the following JavaScript code snippet:

let nextNumber = counters.inc("counter1");

An example of what the counters.json file could look like:

{
    "counter1": 177,
    "anotherCounter": 3
}

The 'increment' function in the 'counters' namespace, which is part of our API code, both increments the counter and returns its new value. This simplifies the process by combining the increment and retrieval operations into a single step.

// Get the current counter value
let currentValue = counters.get("name");

// Reset a counter
counters.set("name", 1000);

The "counters.inc()" function in our API provides a safe and efficient way to interact with counters, handling the necessary file operations and ensuring thread safety. By using this function, you can avoid direct manipulation of the counters.json file, which could lead to race conditions or inconsistent states.

This approach simplifies the API by providing a single function 'counters.inc()' that both updates the counter and returns its new value, eliminating the need for separate 'get' and 'set' operations in most cases. The 'counters' namespace in our API helps organize these related functions and makes the code more readable and maintainable.