|
| 1 | +import { publishEdit } from '../ipfs.js'; |
| 2 | +import { Triple } from '../triple.js'; |
| 3 | +import type { SetTripleOp } from '../types.js'; |
| 4 | +import { DEFAULT_API_HOST } from './constants.js'; |
| 5 | + |
| 6 | +type Params = { |
| 7 | + id: string; |
| 8 | + spaceId: string; |
| 9 | + accountId: string; |
| 10 | + data: { |
| 11 | + [filedName: string]: string; |
| 12 | + }; |
| 13 | + mapping: { |
| 14 | + [filedName: string]: string; |
| 15 | + }; |
| 16 | + options?: { |
| 17 | + apiHost?: string; |
| 18 | + network?: 'TESTNET' | 'MAINNET'; |
| 19 | + }; |
| 20 | +}; |
| 21 | + |
| 22 | +export const createEntity = async ({ id, data, spaceId, accountId, mapping, options }: Params) => { |
| 23 | + const ops: SetTripleOp[] = []; |
| 24 | + const apiHost = options?.apiHost || DEFAULT_API_HOST; |
| 25 | + const network = options?.network || 'TESTNET'; |
| 26 | + for (const [fieldName, value] of Object.entries(data)) { |
| 27 | + const attributeId = mapping[fieldName]; |
| 28 | + if (!attributeId) { |
| 29 | + throw new Error(`Attribute ID for field ${fieldName} not found`); |
| 30 | + } |
| 31 | + let attributeValueType: 'TEXT' | 'CHECKBOX' | 'NUMBER' | 'URL' | 'POINT'; |
| 32 | + switch (typeof value) { |
| 33 | + case 'string': |
| 34 | + attributeValueType = 'TEXT'; |
| 35 | + break; |
| 36 | + case 'boolean': |
| 37 | + attributeValueType = 'CHECKBOX'; |
| 38 | + break; |
| 39 | + case 'number': |
| 40 | + attributeValueType = 'NUMBER'; |
| 41 | + break; |
| 42 | + default: |
| 43 | + throw new Error('Not implemented value type'); |
| 44 | + } |
| 45 | + const setTripleOp: SetTripleOp = Triple.make({ |
| 46 | + entityId: id, |
| 47 | + attributeId, |
| 48 | + value: { |
| 49 | + type: attributeValueType, |
| 50 | + value, |
| 51 | + }, |
| 52 | + }); |
| 53 | + |
| 54 | + ops.push(setTripleOp); |
| 55 | + } |
| 56 | + |
| 57 | + const cid = await publishEdit({ |
| 58 | + name: 'Edit name', |
| 59 | + ops, |
| 60 | + author: accountId, |
| 61 | + }); |
| 62 | + |
| 63 | + const result = await fetch(`${apiHost}/space/${spaceId}/edit/calldata`, { |
| 64 | + method: 'POST', |
| 65 | + body: JSON.stringify({ |
| 66 | + cid: cid, |
| 67 | + network, |
| 68 | + }), |
| 69 | + }); |
| 70 | + |
| 71 | + const jsonResult = await result.json(); |
| 72 | + return jsonResult; |
| 73 | + |
| 74 | + // TODO add walletClient.sendTransaction |
| 75 | +}; |
0 commit comments