launchdarkly / swift-eventsource

Server-sent events (SSE) client implementation in Swift for iOS, macOS, tvOS, and watchOS
https://launchdarkly.github.io/swift-eventsource/
Other
187 stars 34 forks source link

[Feat Request] Read response data on error #66

Closed jeongshin closed 11 months ago

jeongshin commented 11 months ago

Is your feature request related to a problem? Please describe.

I trying to read response data (json error message from server) when request error occurred while creating connection. But only responseCode is available for UnsuccessfulResponseError.

Describe the solution you'd like

as-is

public class UnsuccessfulResponseError: Error {
    /// The HTTP response code received.
    public let responseCode: Int

    /**
     Constructor for an `UnsuccessfulResponseError`.

     - Parameter responseCode: The HTTP response code of the unsuccessful response.
     */
    public init(responseCode: Int) {
        self.responseCode = responseCode
    }
}

to-be


public class UnsuccessfulResponseError: Error {
    /// The HTTP response code received.
    public let responseCode: Int

    public let data: Data?
    public let response: Response?
    public let error: Error?
}

Can UnsuccessfulResponseError be like this?

I'm newbie learning swift and I tried to solve this by myself but failed to do so

https://github.com/launchdarkly/swift-eventsource/pull/65

Describe alternatives you've considered

Additional context

tanderson-ld commented 11 months ago

Hello @jeongshin , could you provide an example of the raw HTTP Response that contains the data? I'm interpreting this as the response body contains error data and that is what you want to pipe through the error object?

jeongshin commented 11 months ago

I'm interpreting this as the response body contains error data and that is what you want to pipe through the error object?

That's correct!

How would you want me to provide raw HTTP response?

Here's my minimal server code for mocking streaming using express.

import bodyParser from 'body-parser';
import express from 'express';
import { concatMap, delay, from, of } from 'rxjs';
import cors from 'cors';

const app = express();

app.use(bodyParser.json());

app.use(cors({ origin: '*' }));

app.use(bodyParser.urlencoded({ extended: false }));

app.listen(3000, () => {
  console.log('start listening');
});

const messages =
  '이제 더이상 ChatGPT의 딱딱하고 한국어가 서투른 서비스를 이용하려고 애쓰지 않아도 됩니다. ChatGPT를 사용하시는 분들에게 최적화되고 발전하고 있는 한국형 AI 뤼튼을 사용해 보시길 권합니다.  진짜 AI는 미치도록 미쳤다 아무래도 회사 집 회사 집 하시는 분들은 AI? 그냥 요즘 애들 이야기 들어보니까 챗지피틴가 피티인가 하는 뭐시기가 요즘 좋다며?하면서 이야기를 하지만 직접 사용해보고 ai에 대해서 조금 더 들어가면  현재도 AI를 어떻게 활용하느냐에 따라서 앞으로 우리가 발전해야 할 시장이나 세상이 달라질 수도 있을 것 같다는 그런 생각이 드는데요 [출처] 뤼튼테크놀로지를 사용 안하고 있다면 인생을 낭비하고 있는 중이다|작성자 부자가될대학생리치원'.split(
    ' '
  );

const headers = {
  'Content-Type': 'text/event-stream; charset=utf-8',
  'Connection': 'keep-alive',
  'Cache-Control': 'no-cache',
};

app.get('/stream', (req, res) => {
  res.writeHead(201, headers);

  console.log('request body from client', req.body, req.headers);

  from(messages)
    .pipe(concatMap((x) => of(x).pipe(delay(100))))
    .subscribe((message) => {
      res.write(
        `data: ${JSON.stringify({
          chunk: message,
        })}\nevent: data\nid: ${new Date().getTime()}\n\n`
      );

      if (messages.findIndex((x) => x === message) === messages.length - 1) {
        res.write(`data: ${JSON.stringify({ end: '[DONE]' })}\n\n`);
      }
    });

  req.on('close', () => {
    console.log('closed connection from client 💥');
  });
});

app.get('/stream/timeout', () => {
  // DO NOTHING
});

// this is error case that I wish to read response message
app.get('/stream/error', (req, res) => {
  console.log('request');
  res.status(503).json({ message: 'custom error message' });
});

I'm sending error message for user as json.

Screenshot 2023-09-21 at 10 46 29 AM Screenshot 2023-09-21 at 10 47 19 AM

Thanks for reply! 🙌

tanderson-ld commented 11 months ago

Hi again @jeongshin . We discussed this on team and concluded that we won't pick up this feature request. The SSE specification does not have provisions for parsing response body content and piping that out through the error mechanisms. You are welcome to fork if you would like! Thank you for using the library and giving us feedback.

jeongshin commented 11 months ago

@tanderson-ld Thanks for the clarification!! 👍