唯杰地图 logo唯杰地图
VJMAP
EN

05_data_storage_kv.js

vjmap-service/examples/nodejs/05_data_storage_kv.js 1.5 KB42 行
原文
// 示例 5:KV 数据存储全流程(单值 / 批量 / 前缀)。
//
// 用法:
//   node 05_data_storage_kv.js
'use strict';

const { makeClient } = require('./_common');

(async () => {
  const svc = makeClient();
  const prefix = 'demo:nb:'; // ':' 作分隔:前缀查询/删除是 SQL LIKE,'_' 会被当通配符

  console.log(`[1/6] 单键写入 ${prefix}user1`);
  await svc.saveCustomData(`${prefix}user1`, { value: JSON.stringify({ name: 'alice', age: 20 }) });

  console.log('[2/6] 单键读取');
  const u1 = await svc.getCustomData(`${prefix}user1`);
  console.log('  ->', u1 && u1.data);

  console.log('[3/6] 批量写入(user2 / user3)');
  await svc.saveMultipleCustomData([
    { key: `${prefix}user2`, value: JSON.stringify({ name: 'bob', age: 30 }) },
    { key: `${prefix}user3`, value: JSON.stringify({ name: 'carol', age: 25 }) },
  ]);

  console.log('[4/6] 列出 prefix 下所有 key');
  const keys = await svc.getCustomDataKeys(prefix);
  console.log('  ->', keys && keys.keys); // 响应字段是 keys(不是 data)

  console.log(`[5/6] 删除单个 ${prefix}user2`);
  await svc.deleteCustomData(`${prefix}user2`);

  console.log('[6/6] 按前缀批量删除');
  await svc.deleteCustomData(prefix, { isPrefix: true });

  const final = await svc.getCustomDataKeys(prefix);
  console.log('  清理后剩余 keys:', (final && final.keys) || []);
})().catch((e) => {
  console.error('失败:', e.body || e.message || e);
  process.exit(1);
});