Skip to content

Commit

Permalink
feat: add simple topics example for web sdk (#1462)
Browse files Browse the repository at this point in the history
  • Loading branch information
rishtigupta authored Nov 5, 2024
1 parent 44be3bf commit 44b5334
Show file tree
Hide file tree
Showing 17 changed files with 3,998 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/web/cache/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
registry=https://registry.npmjs.org/
3 changes: 3 additions & 0 deletions examples/web/topics/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
dist
**/*.d.ts
63 changes: 63 additions & 0 deletions examples/web/topics/.eslintrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
{
"root": true,
"env": {
"es2021": true
},
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended",
"plugin:@typescript-eslint/recommended-requiring-type-checking",
"plugin:import/recommended",
"plugin:prettier/recommended",
"plugin:node/recommended"
],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 12,
"project": "./tsconfig.json"
},
"plugins": ["@typescript-eslint"],
"rules": {
"semi": ["error", "always"],
"import/no-extraneous-dependencies": ["error", {}],
"node/no-unsupported-features/es-syntax": "off",
"node/no-missing-import": [
"error",
{
"tryExtensions": [".js", ".ts", ".json", ".node"]
}
],
"prettier/prettier": "error",
"block-scoped-var": "error",
"eqeqeq": "error",
"no-var": "error",
"prefer-const": "error",
"eol-last": "error",
"prefer-arrow-callback": "error",
"no-trailing-spaces": "error",
"quotes": ["warn", "single", {"avoidEscape": true}],
"no-restricted-properties": [
"error",
{
"object": "describe",
"property": "only"
},
{
"object": "it",
"property": "only"
}
],
// async without await is often an error and in other uses it obfuscates
// the intent of the developer. Functions are async when they want to await.
"require-await": "error",
"import/no-duplicates": "error",
"@typescript-eslint/switch-exhaustiveness-check": "error"
},
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".jsx", ".ts", ".tsx"]
}
}
}
}
1 change: 1 addition & 0 deletions examples/web/topics/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
advanced-middlewares-example-metrics.csv
2 changes: 2 additions & 0 deletions examples/web/topics/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*.ts
!*.d.ts
1 change: 1 addition & 0 deletions examples/web/topics/.npmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
registry=https://registry.npmjs.org/
8 changes: 8 additions & 0 deletions examples/web/topics/.prettierrc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
{
"bracketSpacing": false,
"singleQuote": true,
"trailingComma": "es5",
"arrowParens": "avoid",
"printWidth": 120
}

95 changes: 95 additions & 0 deletions examples/web/topics/README.ja.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,95 @@
# Node.js クライアント SDK

_他言語バージョンもあります_[English](README.md)

<br>

## SDK のコード例を実行する

- Node バージョン 16 もしくはそれ以上
- Momento オーストークンが必要です。トークン発行は[Momento CLI](https://github.com/momentohq/momento-cli)から行えます。

```bash
cd examples
npm install

# SDKコード例を実行する
MOMENTO_API_KEY=<YOUR API KEY> npm run example
```

SDK コード例: [index.ts](index.ts)

## SDK を自身のプロジェクトで使用する

### インストール方法

```bash
npm install @gomomento/sdk
```

### 使用方法

```typescript
import { CacheClient, CacheGetStatus } from "@gomomento/sdk";

// ユーザーのMomentoオーストークン
const apiKey = process.env.MOMENTO_API_KEY;

// Momentoをイニシャライズする
const DEFAULT_TTL = 60; // デフォルトTTLは60秒
const momento = new CacheClient(apiKey, DEFAULT_TTL);

// "myCache"という名のキャッシュを作成する
const CACHE_NAME = "myCache";
await momento.createCache(CACHE_NAME);

// デフォルトTTLでキーを設定
await momento.set(CACHE_NAME, "key", "value");
const res = await momento.get(CACHE_NAME, "key");
console.log("result: ", res.text());

// TTL5秒でキーを設定
await momento.set(CACHE_NAME, "key2", "value2", 5);

// 永久にキャッシュを削除する
await momento.deleteCache(CACHE_NAME);
```

Momento はバイト型のストアもサポートしています

```typescript
const key = new Uint8Array([109, 111, 109, 101, 110, 116, 111]);
const value = new Uint8Array([
109, 111, 109, 101, 110, 116, 111, 32, 105, 115, 32, 97, 119, 101, 115, 111,
109, 101, 33, 33, 33,
]);
await momento.set("cache", key, value, 50);
await momento.get("cache", key);
```

キャッシュミスの対応

```typescript
const res = await momento.get("cache", "non-existent key");
if (res.status === CacheGetStatus.Miss) {
console.log("cache miss");
}
```

ファイルのストア

```typescript
const buffer = fs.readFileSync("./file.txt");
const filebytes = Uint8Array.from(buffer);
const cacheKey = "key";
const cacheName = "my example cache";

// キャッシュにファイルをストアする
await momento.set(cacheName, cacheKey, filebytes);

// ファイルをキャッシュから取り出す
const getResp = await momento.get(cacheName, cacheKey);

// ファイルをディスクに書き込む
fs.writeFileSync("./file-from-cache.txt", Buffer.from(getResp.bytes()));
```
37 changes: 37 additions & 0 deletions examples/web/topics/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
<img src="https://docs.momentohq.com/img/momento-logo-forest.svg" alt="logo" width="400"/>

[![project status](https://momentohq.github.io/standards-and-practices/badges/project-status-official.svg)](https://github.com/momentohq/standards-and-practices/blob/main/docs/momento-on-github.md)
[![project stability](https://momentohq.github.io/standards-and-practices/badges/project-stability-stable.svg)](https://github.com/momentohq/standards-and-practices/blob/main/docs/momento-on-github.md)


# Momento JavaScript Web SDK - Basic Topic Examples

_Read this in other languages_: [日本語](README.ja.md)

<br>

## Example Requirements

- Node version 16 or higher is required
- A Momento API key is required, you can generate one using the [Momento CLI](https://github.com/momentohq/momento-cli)

To run any of the examples you will need to install the dependencies once first:

```bash
npm install
```

## Running the Basic Example

```bash
# Run example code
MOMENTO_API_KEY=<YOUR API KEY> npm run example
```

Example Code: [basic.ts](basic.ts)


If you have questions or need help experimenting further, please reach out to us!

----------------------------------------------------------------------------------------
For more info, visit our website at [https://gomomento.com](https://gomomento.com)!
32 changes: 32 additions & 0 deletions examples/web/topics/README.template.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{{ ossHeader }}

# Momento JavaScript Web SDK - Basic Topics Examples

_Read this in other languages_: [日本語](README.ja.md)

<br>

## Example Requirements

- Node version 16 or higher is required
- A Momento API key is required, you can generate one using the [Momento CLI](https://github.com/momentohq/momento-cli)

To run any of the examples you will need to install the dependencies once first:

```bash
npm install
```

## Running the Basic Example

```bash
# Run example code
MOMENTO_API_KEY=<YOUR API KEY> npm run example
```

Example Code: [basic.ts](basic.ts)


If you have questions or need help experimenting further, please reach out to us!

{{ ossFooter }}
82 changes: 82 additions & 0 deletions examples/web/topics/basic.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
import {
CacheClient,
CreateCacheResponse,
SubscribeCallOptions,
TopicClient,
TopicItem,
TopicPublishResponse,
TopicSubscribe,
TopicSubscribeResponse,
} from '@gomomento/sdk-web';
import {initJSDom} from './utils/jsdom';

async function main() {
// Because the Momento Web SDK is intended for use in a browser, we use the JSDom library to set up an environment
// that will allow us to use it in a node.js program.
initJSDom();
const cacheClient = new CacheClient({
defaultTtlSeconds: 60,
});
const topicClient = new TopicClient();

const createCacheResponse = await cacheClient.createCache('cache');
switch (createCacheResponse.type) {
case CreateCacheResponse.AlreadyExists:
console.log('cache already exists');
break;
case CreateCacheResponse.Success:
console.log('cache created');
break;
case CreateCacheResponse.Error:
throw createCacheResponse.innerException();
}

console.log("Subscribing to topic 'topic'");
const subscribeCallOptions: SubscribeCallOptions = {
onItem: (item: TopicItem) => {
console.log(`Received message: ${item.valueString()}`);
},
onError: (error: TopicSubscribe.Error, subscription: TopicSubscribe.Subscription) => {
console.error(`Error: ${error.message()}`);
subscription.unsubscribe();
},
};
let subscription: TopicSubscribe.Subscription | undefined;
const subscribeResponse = await topicClient.subscribe('cache', 'topic', subscribeCallOptions);
switch (subscribeResponse.type) {
case TopicSubscribeResponse.Subscription: {
console.log("Subscribed to topic 'topic'");
subscription = subscribeResponse;
break;
}
case TopicSubscribeResponse.Error: {
console.error(`Error: ${subscribeResponse.message()}`);
break;
}
}

console.log('Publishing message to topic');
const publishResponse = await topicClient.publish('cache', 'topic', 'Hello, world!');
switch (publishResponse.type) {
case TopicPublishResponse.Success: {
console.log('Message published successfully to topic "topic"');
break;
}
case TopicPublishResponse.Error: {
console.error(`Error: ${publishResponse.message()}`);
break;
}
}

console.log("Unsubscribing from topic 'topic'");
subscription?.unsubscribe();
}

main()
.then(() => {
console.log('success!!');
})
.catch((e: Error) => {
console.error(`Uncaught exception while running example: ${e.message}`);
throw e;
});
8 changes: 8 additions & 0 deletions examples/web/topics/jest.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
module.exports = {
testEnvironment: 'node',
roots: ['<rootDir>/test'],
testMatch: ['**/*.test.ts'],
transform: {
'^.+\\.tsx?$': 'ts-jest',
},
};
Loading

0 comments on commit 44b5334

Please sign in to comment.