BasePlatformService.js 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  1. const Fastify = require('fastify');
  2. const RabbitMQConnector = require('./RabbitMQConnector');
  3. const { createLogger } = require('./logger');
  4. /**
  5. * BasePlatformService — tüm platform servisleri bu sınıftan extend eder.
  6. *
  7. * Her platform servisi şu metodları override etmeli:
  8. * - fetchFeed() → platform API'sinden feed çeker
  9. * - publishPost(post) → platforma içerik gönderir
  10. * - getStatus() → bağlantı durumu döner
  11. * - authenticate(code) → OAuth callback işler
  12. */
  13. class BasePlatformService extends RabbitMQConnector {
  14. constructor(platformName) {
  15. super();
  16. this.platformName = platformName;
  17. this.log = createLogger(platformName);
  18. this.app = Fastify({ logger: this.log });
  19. this._setupRoutes();
  20. }
  21. /** HTTP route'ları kaydet — platform servisleri override edebilir */
  22. _setupRoutes() {
  23. this.app.get('/status', async (request) => {
  24. const workspaceId = request.headers['x-workspace-id'] || 'default';
  25. return this.getStatus(workspaceId);
  26. });
  27. this.app.get('/feed', async (request, reply) => {
  28. const workspaceId = request.headers['x-workspace-id'] || 'default';
  29. try {
  30. const items = await this.fetchFeed({ ...request.query, workspaceId });
  31. return { success: true, platform: this.platformName, count: items.length, items };
  32. } catch (err) {
  33. reply.code(500).send({ success: false, error: err.message });
  34. }
  35. });
  36. this.app.post('/post', async (request, reply) => {
  37. const workspaceId = request.headers['x-workspace-id'] || 'default';
  38. try {
  39. const result = await this.publishPost({ ...request.body, workspaceId });
  40. return { success: true, platform: this.platformName, result };
  41. } catch (err) {
  42. reply.code(500).send({ success: false, error: err.message });
  43. }
  44. });
  45. this.app.get('/auth/callback', async (request, reply) => {
  46. try {
  47. const result = await this.authenticate(request.query);
  48. return { success: true, platform: this.platformName, result };
  49. } catch (err) {
  50. reply.code(500).send({ success: false, error: err.message });
  51. }
  52. });
  53. }
  54. /** HTTP sunucusunu başlat */
  55. async start(port = 3000) {
  56. await this.connect();
  57. await this.app.listen({ port, host: '0.0.0.0' });
  58. this.app.log.info({ action: 'service_start', port, outcome: 'success' }, `${this.platformName} service started`);
  59. }
  60. // ─── Alt sınıfların override edeceği metodlar ───────────────────────────────
  61. /** @returns {{ connected: boolean, platform: string, username?: string }} */
  62. async getStatus() {
  63. return { connected: false, platform: this.platformName };
  64. }
  65. /** @returns {Array<FeedItem>} normalize edilmiş feed öğeleri */
  66. async fetchFeed() {
  67. throw new Error(`[${this.platformName}] fetchFeed() implement edilmedi`);
  68. }
  69. /** @param {{ content: string, media?: Array, tags?: Array }} post */
  70. async publishPost() {
  71. throw new Error(`[${this.platformName}] publishPost() implement edilmedi`);
  72. }
  73. /** @param {{ code: string, state?: string }} query — OAuth callback params */
  74. async authenticate() {
  75. throw new Error(`[${this.platformName}] authenticate() implement edilmedi`);
  76. }
  77. // ─── Yardımcı metodlar ───────────────────────────────────────────────────────
  78. /**
  79. * Normalize edilmiş feed öğesi oluştur.
  80. * Platform servisleri bu şablonu kullanarak veriyi standartlaştırır.
  81. */
  82. normalizeFeedItem({
  83. originalId,
  84. author,
  85. content,
  86. contentHtml = null,
  87. media = [],
  88. links = [],
  89. platformTags = [],
  90. metrics = {},
  91. url = null,
  92. createdAt = new Date(),
  93. }) {
  94. return {
  95. platform: this.platformName,
  96. originalId: String(originalId),
  97. author: {
  98. name: author.name || '',
  99. username: author.username || '',
  100. avatar: author.avatar || null,
  101. profileUrl: author.profileUrl || null,
  102. },
  103. content,
  104. contentHtml,
  105. media,
  106. links,
  107. tags: [],
  108. platformTags,
  109. metrics: {
  110. likes: metrics.likes || 0,
  111. comments: metrics.comments || 0,
  112. shares: metrics.shares || 0,
  113. views: metrics.views || 0,
  114. bookmarks: metrics.bookmarks || 0,
  115. },
  116. url,
  117. createdAt: new Date(createdAt),
  118. fetchedAt: new Date(),
  119. };
  120. }
  121. }
  122. module.exports = BasePlatformService;