UNPKG

wikibase-edit

Version:

Edit Wikibase from NodeJS

50 lines 1.96 kB
import config from 'config'; import wbkFactory, {} from 'wikibase-sdk'; import WBEdit from '../../../src/lib/index.js'; import { customFetch } from '../../../src/lib/request/fetch.js'; import { randomString } from '../../unit/utils.js'; const wbk = wbkFactory({ instance: config.instance }); const sandboxProperties = {}; const wbEdit = WBEdit(config); export async function getProperty({ datatype, reserved }) { if (!datatype) throw new Error('missing datatype'); if (reserved) return createProperty(datatype); const property = await _getProperty(datatype); sandboxProperties[datatype] = property; return property; } async function _getProperty(datatype) { const pseudoPropertyId = getPseudoPropertyId(datatype); const cachedPropertyId = sandboxProperties[pseudoPropertyId]; if (cachedPropertyId) return cachedPropertyId; const foundPropertyId = await findOnWikibase(pseudoPropertyId); if (foundPropertyId) return foundPropertyId; else return createProperty(datatype); } async function findOnWikibase(pseudoPropertyId) { const url = wbk.searchEntities({ search: pseudoPropertyId, type: 'property' }); const body = await customFetch(url).then(res => res.json()); const firstWbResult = body.search[0]; if (firstWbResult) return firstWbResult; } async function createProperty(datatype) { const pseudoPropertyId = getPseudoPropertyId(datatype); const res = await wbEdit.entity.create({ type: 'property', datatype, labels: { // Including a random string to avoid conflicts in case a property with that pseudoPropertyId // already exist but wasn't found due to a problem in ElasticSearch en: `${pseudoPropertyId} (${randomString()})`, }, }); return res.entity; } const getPseudoPropertyId = (datatype) => `${datatype} sandbox property`; //# sourceMappingURL=get_property.js.map