export function endStreamFromJson()

in packages/dubbo/src/protocol-triple/end-stream.ts [50:96]


export function endStreamFromJson(
  data: Uint8Array | string
): EndStreamResponse {
  const parseErr = new ConnectError("invalid end stream", Code.InvalidArgument);
  let jsonValue: JsonValue;
  try {
    // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment
    jsonValue = JSON.parse(
      typeof data == "string" ? data : new TextDecoder().decode(data)
    );
  } catch (e) {
    throw parseErr;
  }
  if (
    typeof jsonValue != "object" ||
    jsonValue == null ||
    Array.isArray(jsonValue)
  ) {
    throw parseErr;
  }
  const metadata = new Headers();
  if ("metadata" in jsonValue) {
    if (
      typeof jsonValue.metadata != "object" ||
      jsonValue.metadata == null ||
      Array.isArray(jsonValue.metadata)
    ) {
      throw parseErr;
    }
    for (const [key, values] of Object.entries(jsonValue.metadata)) {
      if (
        !Array.isArray(values) ||
        values.some((value) => typeof value != "string")
      ) {
        throw parseErr;
      }
      for (const value of values) {
        metadata.append(key, value as string);
      }
    }
  }
  const error =
    "error" in jsonValue
      ? errorFromJson(jsonValue.error, metadata, parseErr)
      : undefined;
  return { metadata, error };
}