Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Javascript client library for the Entity API #14

Draft
wants to merge 2 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions clients/javascript/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
module.exports = {
env: {
browser: true,
es2021: true,
},
extends: ["standard-with-typescript", "prettier"],
overrides: [],
parserOptions: {
ecmaVersion: "latest",
},
rules: {},
};
147 changes: 147 additions & 0 deletions clients/javascript/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
# Created by https://www.toptal.com/developers/gitignore/api/node
# Edit at https://www.toptal.com/developers/gitignore?templates=node

### Node ###
# Logs
logs
*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
lerna-debug.log*
.pnpm-debug.log*

# Diagnostic reports (https://nodejs.org/api/report.html)
report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json

# Runtime data
pids
*.pid
*.seed
*.pid.lock

# Directory for instrumented libs generated by jscoverage/JSCover
lib-cov

# Coverage directory used by tools like istanbul
coverage
*.lcov

# nyc test coverage
.nyc_output

# Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files)
.grunt

# Bower dependency directory (https://bower.io/)
bower_components

# node-waf configuration
.lock-wscript

# Compiled binary addons (https://nodejs.org/api/addons.html)
build/Release

# Dependency directories
node_modules/
jspm_packages/

# Snowpack dependency directory (https://snowpack.dev/)
web_modules/

# TypeScript cache
*.tsbuildinfo

# Optional npm cache directory
.npm

# Optional eslint cache
.eslintcache

# Optional stylelint cache
.stylelintcache

# Microbundle cache
.rpt2_cache/
.rts2_cache_cjs/
.rts2_cache_es/
.rts2_cache_umd/

# Optional REPL history
.node_repl_history

# Output of 'npm pack'
*.tgz

# Yarn Integrity file
.yarn-integrity

# dotenv environment variable files
.env
.env.development.local
.env.test.local
.env.production.local
.env.local

# parcel-bundler cache (https://parceljs.org/)
.cache
.parcel-cache

# Next.js build output
.next
out

# Nuxt.js build / generate output
.nuxt
dist

# Gatsby files
.cache/
# Comment in the public line in if your project uses Gatsby and not Next.js
# https://nextjs.org/blog/next-9-1#public-directory-support
# public

# vuepress build output
.vuepress/dist

# vuepress v2.x temp and cache directory
.temp

# Docusaurus cache and generated files
.docusaurus

# Serverless directories
.serverless/

# FuseBox cache
.fusebox/

# DynamoDB Local files
.dynamodb/

# TernJS port file
.tern-port

# Stores VSCode versions used for testing VSCode extensions
.vscode-test

# yarn v2
.yarn/cache
.yarn/unplugged
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

### Node Patch ###
# Serverless Webpack directories
.webpack/

# Optional stylelint cache

# SvelteKit build / generate output
.svelte-kit

# End of https://www.toptal.com/developers/gitignore/api/node

# Typescript generated output
lib/
1 change: 1 addition & 0 deletions clients/javascript/.nvmrc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
v18.12.1
37 changes: 37 additions & 0 deletions clients/javascript/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
{
"name": "@moonstream/entity",
"version": "0.0.1",
"description": "Client library for the Moonstream Entity API",
"main": "lib/index.js",
"scripts": {
"test": "exit 0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/bugout-dev/entity.git"
},
"keywords": [
"moonstream",
"web3",
"crypto",
"ethereum"
],
"author": "Moonstream Engineering ([email protected])",
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/bugout-dev/entity/issues"
},
"homepage": "https://github.com/bugout-dev/entity#readme",
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.47.0",
"@typescript-eslint/parser": "^5.47.0",
"eslint": "^8.30.0",
"eslint-config-prettier": "^8.5.0",
"eslint-config-standard-with-typescript": "^24.0.0",
"eslint-plugin-import": "^2.26.0",
"eslint-plugin-n": "^15.6.0",
"eslint-plugin-promise": "^6.1.1",
"prettier": "^2.8.1",
"typescript": "^4.9.4"
}
}
48 changes: 48 additions & 0 deletions clients/javascript/src/entity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
export interface Collection {
collectionId?: string;
name: string;
}

type EntityFieldValue = string | number | boolean | EntityFieldValue[];

type EntityField = { [key: string]: EntityFieldValue };

export interface Entity {
address: string;
blockchain: string;
name: string;
requiredFields: EntityField[];
content: EntityField;
}

export interface EntityResponse {
entity_id: string;
collection_id: string;
address: string;
blockchain: string;
name: string;
required_fields: EntityField[];
secondary_fields: EntityField;
}

export function createEntityRequest(entity: Entity): any {
let requestData = {
address: entity.address,
blockchain: entity.blockchain,
name: entity.name,
required_fields: entity.requiredFields,
...entity.content,
};
return requestData;
}

export function parseEntityResponse(responseData: EntityResponse): Entity {
let entity: Entity = {
address: responseData.address,
blockchain: responseData.blockchain,
name: responseData.name,
requiredFields: responseData.required_fields,
content: responseData.secondary_fields,
};
return entity;
}
148 changes: 148 additions & 0 deletions clients/javascript/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import {
Collection,
Entity,
EntityResponse,
createEntityRequest,
parseEntityResponse,
} from "./entity";

export class EntityClient {
accessToken: string;
apiUrl: string;

constructor(accessToken: string, apiUrl?: string) {
this.accessToken = accessToken;
this.apiUrl = apiUrl
? apiUrl.replace(/\/+$/, "")
: "https://api.moonstream.to/entity";
}

authorizationValue(): string {
return `Bearer ${this.accessToken}`;
}

standardHeaders(): { [key: string]: string } {
return {
Authorization: this.authorizationValue(),
"Content-Type": "application/json",
};
}

async createCollection(name: string): Promise<Collection> {
const response = await fetch(`${this.apiUrl}/collections`, {
method: "POST",
headers: this.standardHeaders(),
body: JSON.stringify({ name }),
});

const collectionRaw = await response.json();
return {
collectionId: collectionRaw.collection_id,
name: collectionRaw.name,
};
}

async listCollections(): Promise<Collection[]> {
const response = await fetch(`${this.apiUrl}/collections`, {
method: "GET",
headers: this.standardHeaders(),
});

const collectionsRaw = await response.json();
return collectionsRaw.collections.map((raw: any) => {
return { collectionId: raw.collection_id, name: raw.name };
});
}

async createEntity(
collectionId: string,
entity: Entity
): Promise<EntityResponse> {
const response = await fetch(
`${this.apiUrl}/collections/${collectionId}/entities`,
{
method: "POST",
headers: this.standardHeaders(),
body: JSON.stringify(createEntityRequest(entity)),
}
);

const createdEntityResponseData: EntityResponse = await response.json();
return createdEntityResponseData;
}

async getEntity(collectionId: string, entityId: string): Promise<Entity> {
const response = await fetch(
`${this.apiUrl}/collections/${collectionId}/entities/${entityId}`,
{ method: "GET", headers: this.standardHeaders() }
);
const entitiesRaw = await response.json();
return entitiesRaw.map((raw: EntityResponse) => parseEntityResponse(raw));
}

async deleteEntity(
collectionId: string,
entityId: string
): Promise<EntityResponse> {
const response = await fetch(
`${this.apiUrl}/collections/${collectionId}/entities/${entityId}`,
{ method: "DELETE", headers: this.standardHeaders() }
);
const entityResponseData: EntityResponse = await response.json();
return entityResponseData;
}

async updateEntity(
collectionId: string,
entityId: string,
entity: Entity
): Promise<EntityResponse> {
const response = await fetch(
`${this.apiUrl}/collections/${collectionId}/entities/${entityId}`,
{
method: "PUT",
headers: this.standardHeaders(),
body: JSON.stringify(createEntityRequest(entity)),
}
);

const updatedEntityResponseData: EntityResponse = await response.json();
return updatedEntityResponseData;
}

async search(
collectionId: string,
requiredFields: string[],
content: string[],
limit?: number,
offset?: number
): Promise<EntityResponse[]> {
limit = limit || 10;
offset = offset || 0;
if (limit < 0) {
throw new Error("limit must be non-negative");
}
if (offset < 0) {
throw new Error("offset must be non-negative");
}
const requiredFieldsQueries = requiredFields.map(
(term) => `required_field=${encodeURIComponent(term)}`
);
const secondaryFieldsQueries = content.map(
(term) => `secondary_field=${encodeURIComponent(term)}`
);
const queryParams = requiredFieldsQueries
.concat(secondaryFieldsQueries)
.join("+");
const response = await fetch(
`${this.apiUrl}/collections/${collectionId}/search?q=${queryParams}`,
{
method: "GET",
headers: this.standardHeaders(),
}
);

const searchResultsResponseData: EntityResponse[] = await response.json();
return searchResultsResponseData;
}
}
Loading