whatwg / xhr

XMLHttpRequest Standard
https://xhr.spec.whatwg.org/
Other
315 stars 131 forks source link

Editorial: less-confusing content-type manipulation algorithm for send() #197

Closed domenic closed 6 years ago

domenic commented 6 years ago

I spent a lot of time staring at send(), both in reviewing #176 and in implementing this in jsdom. I think the algorithm is too confusing mainly because it doesn't make it clear that the purpose is setting and manipulating the Content-Type header.

Thus, I propose this replacement for the current algorithm. I've written it in pseudo-JS since that was easier for me to rearrange things:


if (body !== null) {
  let extractedMIMEType = null;

  switch (body) {
    case Document:
      request.body = body, serialized, converted to unicode, and utf-8 encoded
    case BodyInit:
      { extractedBody, extractedMIMEType } = extractBody(body);
      request.body = extractedBody;
  }

  if (authorRequestHeaders.contains("Content-Type")) {
    if (body is Document or body is string) {
      let originalAuthorContentType = authorRequestHeaders.get("Content-Type");
      let contentTypeRecord = MIMEType.parse(contentTypeRecord);
      if (contentTypeRecord !== failure && contentTypeRecord.parameters.has("charset")) {
        contentTypeRecord.parameters.set("charset", "UTF-8");
        let newContentTypeSerialized = contentTypeRecord.serialize();
        authorRequestHeaders.set("Content-Type", newContentTypeSerialized);
      }
    }
  } else {
    if (body is HTML document) {
      authorRequestHeaders.set("Content-Type", "text/html;charset=UTF-8");
    }
    if (body is XML document) {
      authorRequestHeaders.set("Content-Type", "application/xml;charset=UTF-8");
    }
    if (extractedMIMEType !== null) {
      authorRequestHeaders.set("Content-Type", extractedMIMEType);
    }
  }
}

The main idea of this rewrite is:

WDYT? I can submit a PR after things settle down, if you like this.

annevk commented 6 years ago

Seems reasonable.