@blocklet/sdk

Blocklet SDK for blocklet developer

Install

yarn add @blocklet/sdk

or

npm install @blocklet/sdk

Auth SDK

Usage

const Auth = require('@blocklet/sdk/service/auth');

const client = new Auth();

const userDid = 'xxxxxxxx';

const { user } = await client.getUser(userDid);

API

client.getUser(did)

Get user by user did

  • @param did string
  • @return { code, user }

client.getOwner()

Get owner of the team

  • @return { code, user }

client.getUsers()

Get users of the app

  • @param paging Object

    • paging.pageSize
    • paging.page
  • @param query Object

    • query.role String Match users by role name
    • $none: Match users which does not have a role
    • query.approved Boolean Match users by approved
    • query.search String Match users by did or fullName
  • @param sort Object

    • sort.createdAt Number
    • sort.updatedAt Number
    • sort.lastLoginAt Number
    • -1: The latest time is at first. 1: The latest time is at last.

  • @return { code, users, paging }
Paging {
  total: number of users
  pageSize: number of users per page
  pageCount: number of page
  page: current page number
}

client.getPermissionsByRole(role)

Get all permissions of a role

  • @param role string
  • @return { code, permissions }

client.getRoles()

Get all roles of the team

  • @return { code, roles }

client.createRole({ name, title, description })

  • @param name string the key of the role, should be unique
  • @param title string
  • @param description string
  • @return { code, role }

client.updateRole(name, { title, description })

  • @param name string the key of the role
  • @param title string
  • @param description string
  • @return { code, role }

client.deleteRole(name, { title, description })

  • @param name string the key of the role
  • @return { code }

client.grantPermissionForRole(role, permission)

  • @param role string the name of the role
  • @param permission string the name of the permission
  • @return { code }

client.revokePermissionFromRole(role, permission)

  • @param role string the name of the role
  • @param permission string the name of the permission
  • @return { code }

client.updatePermissionsForRole(role, permissions)

Full update permissions of a role

  • @param role string the name of the role
  • @param permissions array<string> name of the permissions
  • @return { code, role }

client.hasPermission(role, permission)

  • @param role string the name of the role
  • @param permission string the name of the permission
  • @return { code, result }

    • result boolean

client.getPermissions()

Get all permissions of the team

  • @return { code, permissions }

client.createPermission({ name, title, description })

  • @param name Permission the key of the permission, should be unique

    • format: <action>_<resource>. e.g. query_article, mutate_user
  • @param description string
  • @return { code, role }

client.updatePermission(name, { title, description })

  • @param name string the key of the role
  • @param title string
  • @param description string
  • @return { code }

client.deletePermission(name, { title, description })

  • @param name string the key of the permission
  • @return { code }

Notification SDK

Usage

const Notification = require('@blocklet/sdk/service/notification');

const userDid = 'xxxxxxxx';

const notification = {
  title: 'xxx',
  body: 'xxx',
  attachments: [
    {
      type: 'asset',
      data: {
        did: 'xxx',
        chainHost: 'https://chainhost',
      },
    },
  ],
  actions: [
    {
      name: 'xxx',
      title: 'Go To Website',
      link: 'https://arcblock.io',
    },
  ],
};

const content = { message: 'this is a message' };
const actions = [];

await Notification.sendToUser(userDid, notification);

await Notification.sendToUser(userDid, [notification, anotherNotification]);
await Notification.sendToUser([userDid, anotherUserDid], notification);
await Notification.sendToUser([userDid, anotherUserDid], [notification, anotherNotification]);

API

notification.sendToUser(receiver, notification)

Send notification to an account

  • receiver string | array<string> required
  • notification object | array<object> required

    • notification.title string
    • notification.body string
    • notification.attachments array<object>
    • attachment.type enum 'asset', 'vc', 'token' required
    • attachment.data object

      • type: text
      • type string
      • message string
      • type: asset
      • did string
      • chainHost string uri
      • type: vc
      • credential object
      • tag string
      • type: token
      • address string did
      • amount string
      • symbol string
      • senderDid string
      • chainHost string
      • decimal integer
    • notification.actions array<object>
    • name string required
    • title string
    • color string
    • bgColor string
    • link string uri

WalletAuthenticator SDK

Usage

const { WalletAuthenticator } = require('@blocklet/sdk');

const authenticator = new WalletAuthenticator();

WalletHandler SDK

Usage

const AuthStorage = require('@arcblock/did-auth-storage-nedb');
const { WalletAuthenticator, WalletHandlers } = require('@blocklet/sdk');

const authenticator = new WalletAuthenticator();

const handlers = new WalletHandlers({
  authenticator,
  tokenGenerator: () => Date.now().toString(),
  tokenStorage: new AuthStorage({
    dbPath: path.join(process.env.BLOCKLET_DATA_DIR, 'auth.db'),
    onload: (err) => {
      if (err) {
        // eslint-disable-next-line no-console
        console.error(`Failed to load database from ${path.join(process.env.BLOCKLET_DATA_DIR, 'auth.db')}`, err);
      }
    },
  }),
});

Database SDK

A database library for develop blocklet, it's a wrapper of nedb. Supply a simpler way to use nedb. Just use new Database([dbName]), or you can pass a object option as second parameter to create a database as origin nedb way new Database([dbName], [options])

Supply full-promise support.

Usage

const { Database } = require('@blocklet/sdk');

(async () => {
  const db1 = new Database('db1');
  const data1 = await db1.find().skip(1).limit(10);

  class MyDatabase extends Database {
    constructor(name) {
      super(name);
    }

    async extraFn() {
      return 'extra';
    }
  }
  const db2 = new MyDatabase('db2');
  const data2 = await db2.find().paginate(1, 10);
  const data2Extra = await db2.extraFn();
})();

getWallet

Usage

const { getWallet } = require('@blocklet/sdk');

// blocklet wallet is an instance of @ocap/wallet
const blockletWallet = getWallet();

env

Usage

const { env } = require('@blocklet/sdk');

const { name, description, isComponent, dataDir, cacheDir } = env;

// wallet is an instance of @ocap/wallet
const { wallet } = env;
const { address, secretKey, publicKey } = wallet;

middlewares

Usage

const express = require('express');
const { middlewares } = require('@blocklet/sdk');

const app = express();

app.get('/', middlewares.user(), (req, res) => {
  const { did, fullName, role } = req.user;
});

app.get('/auth1', middlewares.auth(), (req, res) => {
  // will return 401 if user is not connected
});

app.get('/auth2', middlewares.auth({ roles: ['admin', 'owner'] }), (req, res) => {
  // will return 401 if user is not connected
  // will return 403 if user role is neither owner nor admin
});

app.get('/auth2', middlewares.auth({ permissions: ['mutate_data', 'query_data'] }), (req, res) => {
  // will return 401 if user is not connected
  // will return 403 if neither 'mutate_data' nor 'query data' in user permissions
});

app.get(
  '/auth3',
  middlewares.auth({ roles: ['admin', 'owner'], permissions: ['mutate_data', 'query_data'] }),
  (req, res) => {
    // will return 401 if user is not connected
    // will return 403 if user role is neither owner nor admin
    // will return 403 if neither 'mutate_data' nor 'query data' in user permissions
  }
);