-
Notifications
You must be signed in to change notification settings - Fork 21
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: add simple topics example for web sdk (#1462)
- Loading branch information
1 parent
44be3bf
commit 44b5334
Showing
17 changed files
with
3,998 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
registry=https://registry.npmjs.org/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
node_modules | ||
dist | ||
**/*.d.ts |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"] | ||
} | ||
} | ||
} | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
advanced-middlewares-example-metrics.csv |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,2 @@ | ||
*.ts | ||
!*.d.ts |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
registry=https://registry.npmjs.org/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,8 @@ | ||
{ | ||
"bracketSpacing": false, | ||
"singleQuote": true, | ||
"trailingComma": "es5", | ||
"arrowParens": "avoid", | ||
"printWidth": 120 | ||
} | ||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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())); | ||
``` |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)! |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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', | ||
}, | ||
}; |
Oops, something went wrong.