@blocklet/sdk

面当开发者的 Blocklet SDK 文档

安装

yarn add @blocklet/sdk

or

npm install @blocklet/sdk

Auth SDK

用法

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()

获取用户列表

  • @param paging Object

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

    • query.role String 按 role name 匹配
    • $none: 匹配没有 role 的用户
    • query.approved Boolean 按 approved 匹配
    • query.search String 按 did 或 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: 全部用户数量
  pageSize: 每页用户数量
  pageCount: 一共有几页
  page: 当前是第几页
}

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

用法

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)

向 DID 发送消息

  • receiver string | array<string> 必填
  • notification object | array<object> 必填

    • notification.title string
    • notification.body string
    • notification.attachments array<object>
    • attachment.type enum 'asset', 'vc', 'token' 必填
    • 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 必填
    • title string
    • color string
    • bgColor string
    • link string uri

WalletAuthenticator SDK

用法

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

const authenticator = new WalletAuthenticator();

WalletHandler SDK

用法

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

用于开发 Blocklet 的数据库,它是 nedb 的包装器。 提供一种更简单的方式来使用 nedb。 只需使用new Database([dbName]),或者你可以传递一个对象选项作为第二个参数来创建一个数据库作为原始 nedb 方式new Database([dbName], [options])

提供 full-promise 支持。

用法

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

用法

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

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

env

用法

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

用法

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) => {
  // 如果用户未连接,将返回 401
});

app.get('/auth2', middlewares.auth({ roles: ['admin', 'owner'] }), (req, res) => {
  // 如果用户未连接,将返回 401
  // 如果用户角色既不是 admin 也不是 owner,将返回 403
});

app.get('/auth2', middlewares.auth({ permissions: ['mutate_data', 'query_data'] }), (req, res) => {
  // 如果用户未连接,将返回 401
  // 如果用户权限中既没有 mutate_data 也没有 query_data ,将返回 403
});

app.get(
  '/auth3',
  middlewares.auth({ roles: ['admin', 'owner'], permissions: ['mutate_data', 'query_data'] }),
  (req, res) => {
    // 如果用户未连接,将返回 401
    // 如果用户角色既不是 admin 也不是 owner,将返回 403
    // 如果用户权限中既没有 mutate_data 也没有 query_data ,将返回 403
  }
);