type CPersistedCounter = {
lastValue: number,
updatedAt: number
}
export class IncrementingCounter {
private resourcePath: string;
private maxId: number;
constructor(resourcePath: string, maxId: number) {
this.resourcePath = resourcePath;
this.maxId = maxId;
}
async getNextId(): Promise<number> {
let currentState: CPersistedCounter;
try {
currentState = await wmill.getResource(this.resourcePath);
} catch {
// If the resource doesn't exist, throw an error
throw new Error(`Resource ${this.resourcePath} not found in workspace`);
}
const newId = (currentState.lastValue + 1) % this.maxId;
const newState: CPersistedCounter = {
updatedAt: Date.now(),
lastValue: newId,
};
// Save the updated state to the Windmill resource - do not need to await because it can proceed in background
wmill.setResource(newState, this.resourcePath);
return newId;
}
}
type CPersistedCounter = {
lastValue: number,
updatedAt: number
}
export class IncrementingCounter {
private resourcePath: string;
private maxId: number;
constructor(resourcePath: string, maxId: number) {
this.resourcePath = resourcePath;
this.maxId = maxId;
}
async getNextId(): Promise<number> {
let currentState: CPersistedCounter;
try {
currentState = await wmill.getResource(this.resourcePath);
} catch {
// If the resource doesn't exist, throw an error
throw new Error(`Resource ${this.resourcePath} not found in workspace`);
}
const newId = (currentState.lastValue + 1) % this.maxId;
const newState: CPersistedCounter = {
updatedAt: Date.now(),
lastValue: newId,
};
// Save the updated state to the Windmill resource - do not need to await because it can proceed in background
wmill.setResource(newState, this.resourcePath);
return newId;
}
}