LSPlugin.Search.ts 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. import { IPluginSearchServiceHooks } from '../LSPlugin'
  2. import { LSPluginUser } from '../LSPlugin.user'
  3. import { isArray, isFunction, mapKeys } from 'lodash-es'
  4. export class LSPluginSearchService {
  5. /**
  6. * @param ctx
  7. * @param serviceHooks
  8. */
  9. constructor(
  10. private ctx: LSPluginUser,
  11. private serviceHooks: IPluginSearchServiceHooks
  12. ) {
  13. ctx._execCallableAPI(
  14. 'register-search-service',
  15. ctx.baseInfo.id,
  16. serviceHooks.name,
  17. serviceHooks.options
  18. )
  19. // hook events TODO: remove listeners
  20. const wrapHookEvent = (k) => `service:search:${k}:${serviceHooks.name}`
  21. Object.entries({
  22. query: {
  23. f: 'onQuery',
  24. args: ['graph', 'q', true],
  25. reply: true,
  26. transformOutput: (data: any) => {
  27. // TODO: transform keys?
  28. if (isArray(data?.blocks)) {
  29. data.blocks = data.blocks.map((it) => {
  30. return it && mapKeys(it, (_, k) => `block/${k}`)
  31. })
  32. }
  33. return data
  34. },
  35. },
  36. rebuildBlocksIndice: { f: 'onIndiceInit', args: ['graph', 'blocks'] },
  37. transactBlocks: { f: 'onBlocksChanged', args: ['graph', 'data'] },
  38. truncateBlocks: { f: 'onIndiceReset', args: ['graph'] },
  39. removeDb: { f: 'onGraph', args: ['graph'] },
  40. }).forEach(([k, v]) => {
  41. const hookEvent = wrapHookEvent(k)
  42. ctx.caller.on(hookEvent, async (payload: any) => {
  43. if (isFunction(serviceHooks?.[v.f])) {
  44. let ret = null
  45. try {
  46. ret = await serviceHooks[v.f].apply(
  47. serviceHooks,
  48. (v.args || []).map((prop: any) => {
  49. if (!payload) return
  50. if (prop === true) return payload
  51. if (payload.hasOwnProperty(prop)) {
  52. const ret = payload[prop]
  53. delete payload[prop]
  54. return ret
  55. }
  56. })
  57. )
  58. if (v.transformOutput) {
  59. ret = v.transformOutput(ret)
  60. }
  61. } catch (e) {
  62. console.error('[SearchService] ', e)
  63. ret = e
  64. } finally {
  65. if (v.reply) {
  66. ctx.caller.call(`${hookEvent}:reply`, ret)
  67. }
  68. }
  69. }
  70. })
  71. })
  72. }
  73. }