### Navigate to example directory and install dependencies Source: https://docs.momentohq.com/cache/integrations/fastly Use this command to change into the example directory and install the required npm dependencies for the Fastly Compute example. ```bash cd client-sdk-javascript/examples/fastly-compute npm install ``` -------------------------------- ### Initialize project and install dependencies Source: https://docs.momentohq.com/objectstore/enhancements/live-reactions Run these commands to initialize a new Node.js project and install the required dependencies: express and @gomomento/sdk. The first command starts an interactive setup wizard, and the second installs the dependencies used in the server-side code. ```bash npm init npm install express @gomomento/sdk ``` -------------------------------- ### Clone and run examples Source: https://docs.momentohq.com/cache/integrations/sequelize Commands to clone the example repository, install dependencies, and run the basic example with a Momento API key. ```bash git clone https://github.com/momentohq/momento-sequelize-cache cd examples npm install MOMENTO_API_KEY="yourApiKey" npm run basic ``` -------------------------------- ### Run the Deno Web SDK example locally Source: https://docs.momentohq.com/cache/integrations/deno Starts the local development server using Deno tasks, accessible at http://localhost:8000. ```bash deno task start ``` -------------------------------- ### Run the Deno HTTP API example locally Source: https://docs.momentohq.com/cache/integrations/deno Start the local development server and check http://localhost:8000 in your browser. ```bash deno task start ``` -------------------------------- ### Install Fastly CLI and Create Profile Source: https://docs.momentohq.com/cache/integrations/fastly Commands to install the Fastly CLI and create a profile, as prompted by the Fastly setup instructions. Run these after saving your Fastly API token. ```bash brew install fastly/tap/fastly fastly profile create ``` -------------------------------- ### Import libraries and set up main function Source: https://docs.momentohq.com/platform/sdks/go/cache.html Sets up the main function with the necessary imports for using the Momento Go SDK. ```go package main import ( "context" "errors" "log" "time" "github.com/google/uuid" "github.com/momentohq/client-sdk-go/auth" "github.com/momentohq/client-sdk-go/config" "github.com/momentohq/client-sdk-go/config/logger" "github.com/momentohq/client-sdk-go/momento" "github.com/momentohq/client-sdk-go/responses" ) func main() { fmt.Println("Hello, world.") } ``` -------------------------------- ### ListLength Rust Example Source: https://docs.momentohq.com/cache/develop/api-reference/list-collections Rust example using cache_client.list_length to get the length of a list and convert it to a u32. Expects a valid list length. ```Rust let length: u32 = cache_client .list_length(cache_name, "list_name") .await? .try_into() .expect("Expected a list length!"); ``` -------------------------------- ### Install Rust and add wasm32-wasip2 target Source: https://docs.momentohq.com/functions/develop/getting-started One-time setup: install Rust via rustup and add the WebAssembly compile target required for Momento Functions. ```bash # Install Rust # https://rustup.rs/ curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh # Add the Functions compile target rustup target add wasm32-wasip2 ``` -------------------------------- ### ListLength JavaScript Example Source: https://docs.momentohq.com/cache/develop/api-reference/list-collections JavaScript example using cacheClient.listLength to get the length of a list. Shows both simplified and pattern-matching styles, handling Hit, Miss, and Error responses. ```JavaScript await cacheClient.listConcatenateBack(cacheName, 'test-list', ['one', 'two', 'three']); const result = await cacheClient.listLength(cacheName, 'test-list'); // simplified style; assume the value was found console.log(`Length of list 'test-list' is: ${result.value()!}`); // pattern-matching style; safer for production code switch (result.type) { case CacheListLengthResponse.Hit: console.log(`Length of list 'test-list' is ${result.length()}`); break; case CacheListLengthResponse.Miss: console.log(`List 'test-list' was not found in cache '${cacheName}'`); break; case CacheListLengthResponse.Error: throw new Error( `An error occurred while attempting to call cacheListLength on list 'test-list' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}` ); } ``` -------------------------------- ### Navigate to Web SDK example directory Source: https://docs.momentohq.com/cache/integrations/cloudflare Command to change into the example directory for the Momento Web SDK in Cloudflare Workers. ```bash cd examples/cloudflare-workers/web-sdk ``` -------------------------------- ### Import libraries and connect to return a CacheClient object Source: https://docs.momentohq.com/platform/sdks/php/cache Sets up the example file by requiring the autoloader, importing Momento classes, and creating a CacheClient with environment variables for API key and endpoint. Also defines a printBanner helper function. ```php getLoggerFactory()->getLogger("ex:"); function printBanner(string $message, LoggerInterface $logger): void { $line = "******************************************************************"; $logger->info($line); $logger->info($message); $logger->info($line); } printBanner("* Momento Example Start *", $logger); ``` -------------------------------- ### Install Momento Go SDK Source: https://docs.momentohq.com/platform/sdks/go/topics.html Run this command in your Go project to install the Momento Go SDK. ```bash go get github.com/momentohq/client-sdk-go ``` -------------------------------- ### Run Express server Source: https://docs.momentohq.com/objectstore/streaming/capture/rtmp Command to start the Express server. Requires FFmpeg installed and FFMPEG_PATH environment variable set. ```bash node app.js ``` -------------------------------- ### Start the server Source: https://docs.momentohq.com/objectstore/enhancements/live-reactions Run this command to start the server locally. The server code should be in server.mjs, and the MOMENTO_API_KEY environment variable should be set in a .env file. This allows the web page to make calls to the server. ```bash node server.mjs ``` -------------------------------- ### Valkey-cli commands and responses Source: https://docs.momentohq.com/self-hosted/valkey-operator/getting-started/quickstart Example valkey-cli session showing PING, SET, and GET commands with their responses. Exit with exit or Ctrl+D. ```text my-cluster.my-app.svc.cluster.local:6379> PING PONG my-cluster.my-app.svc.cluster.local:6379> SET hello world OK my-cluster.my-app.svc.cluster.local:6379> GET hello "world" ``` -------------------------------- ### Start Fastly development server Source: https://docs.momentohq.com/cache/integrations/fastly Run this command to start the local development server. Navigate to localhost:7676 to check that the application is working. ```bash fastly compute serve ``` -------------------------------- ### SortedSetGetRank - Rust Source: https://docs.momentohq.com/cache/develop/api-reference/sorted-set-collections Gets the rank of an element in a sorted set using Rust. The example shows the call and converts the result to a u64. ```Rust let rank: u64 = cache_client .sorted_set_get_rank(cache_name, "sorted_set_name", "value1") .await? .try_into() .expect("Expected a rank!"); ``` -------------------------------- ### SortedSetGetRank - JavaScript Source: https://docs.momentohq.com/cache/develop/api-reference/sorted-set-collections Gets the rank of an element in a sorted set. The example puts elements, then retrieves the rank and handles hit/miss/error responses. ```JavaScript await cacheClient.sortedSetPutElements( cacheName, 'test-sorted-set', new Map([ ['key1', 10], ['key2', 20], ['key3', 30], ]) ); const result = await cacheClient.sortedSetGetRank(cacheName, 'test-sorted-set', 'key2'); // simplified style; assume the value was found console.log(`Element with value 'key1' has rank: ${result.rank()!}`); // pattern-matching style; safer for production code switch (result.type) { case CacheSortedSetGetRankResponse.Hit: console.log(`Element with value 'key1' has rank: ${result.rank()}`); break; case CacheSortedSetGetRankResponse.Miss: console.log(`Sorted Set 'test-sorted-set' was not found in cache '${cacheName}'`); break; case CacheSortedSetGetRankResponse.Error: throw new Error( `An error occurred while attempting to call cacheSortedSetFetchGetRank on sorted set 'test-sorted-set' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}` ); } ``` -------------------------------- ### Navigate to the Deno HTTP API example directory Source: https://docs.momentohq.com/cache/integrations/deno Change to the example directory for the Deno HTTP API. ```bash cd client-sdk-javascript/examples/deno/http-api ``` -------------------------------- ### Java: Construct a CacheClient Source: https://docs.momentohq.com/cache/develop Example of creating a Momento CacheClient in Java using try-with-resources, with CredentialProvider.fromEnvVarV2(), Configurations.Laptop.v1(), and a 60-second TTL. ```java try (CacheClient cacheClient = CacheClient.create( CredentialProvider.fromEnvVarV2(), Configurations.Laptop.v1(), Duration.ofSeconds(60))) { // ... } ``` -------------------------------- ### SortedSetLengthByScore Rust Example Source: https://docs.momentohq.com/cache/develop/api-reference/sorted-set-collections Demonstrates using the Momento Rust client to get the length of a sorted set within a score range. The example creates a SortedSetLengthByScoreRequest with inclusive min and max scores, sends it, and converts the result to a u32, expecting a list length. ```Rust let request = SortedSetLengthByScoreRequest::new(cache_name, "sorted_set_name") .min_score(Some(ScoreBound::Inclusive(0.0))) .max_score(Some(ScoreBound::Inclusive(100.0))); let length: u32 = cache_client .send_request(request) .await? .try_into() .expect("Expected a list length!"); ``` -------------------------------- ### PHP: Construct a CacheClient Source: https://docs.momentohq.com/cache/develop Example of creating a Momento CacheClient in PHP using Laptop::latest(), CredentialProvider::fromEnvironmentVariablesV2(), and a 60-second TTL. ```php new CacheClient( Laptop::latest(), CredentialProvider::fromEnvironmentVariablesV2(), 60 ); ``` -------------------------------- ### SortedSetGetRank - Elixir Source: https://docs.momentohq.com/cache/develop/api-reference/sorted-set-collections Gets the rank of an element in a sorted set using Elixir. The example puts elements, then retrieves the rank and handles hit/miss/error cases. ```Elixir {:ok, _} = Momento.CacheClient.sorted_set_put_elements(client, "test-cache", "test-sorted-set", [ {"key1", 10.0}, {"key2", 20.0} ]) case Momento.CacheClient.sorted_set_get_rank(client, "test-cache", "test-sorted-set", "key1") do {:ok, hit} -> IO.puts("Element with value 'key1' has rank: #{hit.rank}") :miss -> IO.puts( "Value 'key1' not found in sorted set, or sorted set 'test-sorted-set' was not found in cache 'test-cache'" ) {:error, error} -> IO.puts( "An error occurred while attempting to get the rank of 'key1' in sorted set 'test-sorted-set' in cache 'test-cache': #{error.error_code}" ) raise error end ``` -------------------------------- ### Create a TopicClient Source: https://docs.momentohq.com/platform/sdks/go/topics.html Creates a TopicClient using environment credentials and default configuration. Panics on error. ```go credProvider, err := auth.NewEnvMomentoV2TokenProvider() if err != nil { panic(err) } topicClient, err = momento.NewTopicClient( config.TopicsDefault(), credProvider, ) if err != nil { panic(err) } ``` -------------------------------- ### Python: Construct a CacheClient Source: https://docs.momentohq.com/cache/develop Example of creating a Momento CacheClient in Python, using a CredentialProvider from environment variables V2 and a Laptop configuration with 60 seconds TTL. ```python await CacheClientAsync.create( Configurations.Laptop.latest(), CredentialProvider.from_environment_variables_v2(), timedelta(seconds=60), ) ``` -------------------------------- ### DictionaryGetFields Rust example Source: https://docs.momentohq.com/cache/develop/api-reference/dictionary-collections Shows how to get multiple fields from a dictionary using dictionary_get_fields. Handles Hit and Miss response types, converting the response to a HashMap. ```Rust let response = cache_client .dictionary_get_fields(cache_name, "dictionary_name", vec!["field1", "field2"]) .await?; match response { DictionaryGetFieldsResponse::Hit { .. } => { let dictionary: HashMap = response .try_into() .expect("I stored a dictionary of strings!"); println!("Fetched dictionary: {dictionary:?}"); } DictionaryGetFieldsResponse::Miss => println!("Cache miss"), } ``` -------------------------------- ### DictionaryGetField Rust example Source: https://docs.momentohq.com/cache/develop/api-reference/dictionary-collections Shows how to get a single field from a dictionary using dictionary_get_field. Handles Hit and Miss response types, converting the value to a String. ```Rust let response = cache_client .dictionary_get_field(cache_name, "dictionary_name", "field") .await?; match response { DictionaryGetFieldResponse::Hit { value } => { let value: String = value.try_into().expect("I stored a string!"); println!("Fetched value: {value}"); } DictionaryGetFieldResponse::Miss => println!("Cache miss"), } ``` -------------------------------- ### Configurations.Laptop.v1() Source: https://docs.momentohq.com/cache/develop/basics/client-configuration-objects Development environment configuration with relaxed timeouts for high network latency. ```javascript Configurations.Laptop.v1(); ``` -------------------------------- ### Example code using MomentoFetcher Source: https://docs.momentohq.com/cache/integrations/deno This code sets, gets, and deletes an item in the cache, then returns an HTML response. It uses the MomentoFetcher class for error handling. ```typescript const momento = new MomentoFetcher(apiKey, endpoint) await momento.set(cacheName, key, value, 10) console.log(`Set the key-value pair in the cache ${cacheName}`) const getRespAfterSet = await momento.get(cacheName, key) console.log(`Fetching the key after setting the value: ${getRespAfterSet}`) await momento.delete(cacheName, key) console.log(`Deleted the key-value pair from the cache ${cacheName}`) return new Response( `Tested the Momento cache using:
Key: ${key} | Value: ${value}`, { status: 200, headers: new Headers({ 'Content-Type': 'text/html; charset=utf-8', }), }, ) ``` -------------------------------- ### DictionaryGetFields JavaScript example Source: https://docs.momentohq.com/cache/develop/api-reference/dictionary-collections Shows how to get multiple fields from a dictionary using dictionaryGetFields. Includes simplified and pattern-matching styles, handling Hit, Miss, and Error response types. ```JavaScript await cacheClient.dictionarySetFields( cacheName, 'test-dictionary', new Map([ ['key1', 'value1'], ['key2', 'value2'], ]) ); const result = await cacheClient.dictionaryGetFields(cacheName, 'test-dictionary', ['key1', 'key2']); // simplified style; assume the value was found console.log(`Got fields from dictionary: ${result.value()!}`); // pattern-matching style; safer for production code switch (result.type) { case CacheDictionaryGetFieldsResponse.Hit: console.log('Values fetched successfully- '); result.valueMap().forEach((value, key) => { console.log(`${key} : ${value}`); }); break; case CacheDictionaryGetFieldsResponse.Miss: console.log(`Dictionary 'test-dictionary' was not found in cache '${cacheName}'`); break; case CacheDictionaryGetFieldsResponse.Error: throw new Error( `An error occurred while attempting to call cacheDictionaryGetFields on dictionary 'test-dictionary' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}` ); } ``` -------------------------------- ### Navigate to Deno Web SDK example directory Source: https://docs.momentohq.com/cache/integrations/deno Changes the current directory to the Deno Web SDK example within the client-sdk-javascript repository. ```bash cd client-sdk-javascript/examples/deno/web-sdk ``` -------------------------------- ### DictionaryGetField JavaScript example Source: https://docs.momentohq.com/cache/develop/api-reference/dictionary-collections Shows how to get a single field from a dictionary using dictionaryGetField. Includes simplified and pattern-matching styles, handling Hit, Miss, and Error response types. ```JavaScript await cacheClient.dictionarySetField(cacheName, 'test-dictionary', 'test-field', 'test-value'); const result = await cacheClient.dictionaryGetField(cacheName, 'test-dictionary', 'test-field'); // simplified style; assume the value was found console.log(`Field 'test-field' fetched from dictionary: ${result.value()!}`); // pattern-matching style; safer for production code switch (result.type) { case CacheDictionaryGetFieldResponse.Hit: console.log( `Field ${result.fieldString()} fetched successfully from cache '${cacheName}' with value: ${result.value()}` ); break; case CacheDictionaryGetFieldResponse.Miss: console.log(`Dictionary 'test-dictionary' was not found in cache '${cacheName}'`); break; case CacheDictionaryGetFieldResponse.Error: throw new Error( `An error occurred while attempting to call cacheDictionaryGetField on dictionary 'test-dictionary' in cache '${cacheName}': ${result.errorCode()}: ${result.toString()}` ); } ``` -------------------------------- ### Install Momento Web SDK Source: https://docs.momentohq.com/platform/sdks/nodejs/topics.html Install the Momento Web SDK in an existing browser application project using npm. ```bash npm install @gomomento/sdk-web ``` -------------------------------- ### Retrieve SortedSet by time range with SortedSetFetchByScore Source: https://docs.momentohq.com/cache/develop/guides/working-with-time-series-data Fetches data from a specified time period using SortedSetFetchByScore. The score range is given as start and end timestamps (1686511076 to 1686597476 in this example). ```javascript const sensor_data = await cacheClient.sortedSetFetchByScore("sensor_data", `${sensor_id}-sensor-data`, 1686511076, 1686597476) ``` -------------------------------- ### Configurations.Laptop.latest Source: https://docs.momentohq.com/cache/develop/basics/client-configuration-objects Development environment configuration with relaxed timeouts for high network latency. ```kotlin Configurations.Laptop.latest ```