All files / src/handlers/api/line/webhook/messages/new route.ts

97.91% Statements 94/96
91.66% Branches 11/12
100% Functions 2/2
97.91% Lines 94/96

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 1201x                       12x 12x 12x 12x 12x 12x 12x 12x   12x   12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x   12x 12x 12x 12x 12x 12x 12x 12x 12x   10x 10x 10x   11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x 11x   11x 11x 11x 1x 1x   9x 11x 1x 11x 8x 8x 8x 8x   9x 9x 9x 9x 9x 9x 9x 9x   11x       9x 9x 9x 9x   9x 9x 9x 9x 9x 9x   9x 11x 11x 11x 11x  
import { Env } from "@/Env";
import { v4 as uuidv4 } from "uuid";
import type { WebhookMessageObject } from "@/types/api";
import { RequestDataParser } from "@/Request";
import { createRedisClientByEnv } from "@/Redis";
import { paths } from "@/types/api.gen";
import { Request, Response } from "express";
import { Logger } from "@/Logger";
 
type GetResponse =
  paths["/api/line/webhook/{channelId}/messages/new"]["get"]["responses"]["200"]["content"]["application/json"];
 
export async function GET(
  env: Env,
  parentLogger: Logger,
  req: Request,
  res: Response
) {
  const requestId = uuidv4();
  const logger = parentLogger.child({ requestId });
 
  const params = new RequestDataParser(req);
 
  const channelId = params.getPathParamAsString("channelId");
  const consumer = params.getQueryParamAsString("consumer");
  const maxCount = params.getQueryParamAsNumberWithDefault("max_count", 0);
  const maxIdleTimeMs = params.getQueryParamAsNumberWithDefault(
    "max_idle_time_ms",
    60000
  );
  const maxDeliveryCount = params.getQueryParamAsNumberWithDefault(
    "max_delivery_count",
    3
  );
  logger.info("received request", {
    channelId,
    consumer,
    maxCount,
    maxIdleTimeMs,
    maxDeliveryCount,
  });
 
  const messages = await readMessages(
    env,
    logger,
    channelId,
    consumer,
    maxCount,
    maxIdleTimeMs,
    maxDeliveryCount
  );
 
  const resObj: GetResponse = { messages };
  res.status(200).json(resObj);
}
 
async function readMessages(
  env: Env,
  logger: Logger,
  channelId: string,
  consumer: string,
  maxCount: number,
  maxIdleTimeMs: number,
  maxDeliveryCount: number
): Promise<WebhookMessageObject[]> {
  const client = createRedisClientByEnv(env, channelId);
  logger.debug("make redis client", {
    redisHost: env.redisHost,
    redisPort: env.redisPort,
    redisStreamName: env.redisStreamPrefixForLine,
    channelId,
    redisGroupName: env.redisGroupNameForLine,
  });
 
  try {
    const entriesCount = await client.countStreamEntries();
    if (entriesCount === 0) {
      return [];
    }
 
    const created = await client.createConsumerGroupIfNotExists();
    if (created) {
      logger.debug(`created consumer group ${env.redisGroupNameForLine}`);
    } else {
      logger.debug(
        `skiped created consumer group ${env.redisGroupNameForLine}, group is exists`
      );
    }
 
    const longPendingMessages = await client.readLongPendingMessages(
      logger,
      consumer,
      maxIdleTimeMs,
      maxCount,
      maxDeliveryCount
    );
    logger.debug("read long pending messages", { longPendingMessages });
 
    if (maxCount && longPendingMessages.length >= maxCount) {
      return longPendingMessages;
    }
 
    const readNewMessagesMaxCount = Math.max(
      maxCount - longPendingMessages.length,
      0
    );
 
    const newMessages = await client.readNewMessages(
      logger,
      consumer,
      readNewMessagesMaxCount
    );
    logger.debug("read new messages", { newMessages });
 
    return longPendingMessages.concat(newMessages);
  } finally {
    await client.disconnect();
  }
}