Add test case for handling multiple content types.

This commit is contained in:
Dillon Kearns 2022-03-09 09:19:46 -08:00
parent ad5f092d06
commit 6e53ce5f74
2 changed files with 70 additions and 0 deletions

View File

@ -156,3 +156,38 @@ it("gives an error when there is no content-type header", () => {
); );
}); });
}); });
it("handles XML body", () => {
cy.request({
method: "POST",
url: "/api/multiple-content-types",
headers: { "Content-Type": "application/xml ; charset=utf-8" },
body: `
<root>
<path>
<to>
<string>
<value>SomeString</value>
</string>
</to>
</path>
</root>
`,
}).then((res) => {
expect(res.headers["content-type"]).to.eq("text/plain");
expect(res.status).to.eq(200);
expect(res.body).to.eq("SomeString");
});
});
it("handles JSON body", () => {
cy.request({
method: "POST",
url: "/api/multiple-content-types",
body: { path: { to: { string: { value: "SomeString" } } } },
}).then((res) => {
expect(res.headers["content-type"]).to.eq("text/plain");
expect(res.status).to.eq(200);
expect(res.body).to.eq("SomeString");
});
});

View File

@ -41,6 +41,7 @@ routes getStaticRoutes htmlToString =
|> ApiRoute.serverRender |> ApiRoute.serverRender
, requestPrinter , requestPrinter
, xmlDecoder , xmlDecoder
, multipleContentTypes
] ]
@ -69,6 +70,40 @@ xmlDecoder =
|> ApiRoute.serverRender |> ApiRoute.serverRender
multipleContentTypes : ApiRoute ApiRoute.Response
multipleContentTypes =
let
dataDecoder : Xml.Decode.Decoder String
dataDecoder =
Xml.Decode.path [ "path", "to", "string", "value" ] (Xml.Decode.single Xml.Decode.string)
in
ApiRoute.succeed
(Request.oneOf
[ Request.map2
(\_ xmlString ->
xmlString
|> Xml.Decode.run dataDecoder
|> Result.Extra.merge
|> Response.plainText
|> DataSource.succeed
)
(Request.expectContentType "application/xml")
Request.expectBody
, Request.map
(\decodedValue ->
decodedValue
|> Response.plainText
|> DataSource.succeed
)
(Request.expectJsonBody (Decode.at [ "path", "to", "string", "value" ] Decode.string))
]
)
|> ApiRoute.literal "api"
|> ApiRoute.slash
|> ApiRoute.literal "multiple-content-types"
|> ApiRoute.serverRender
requestPrinter : ApiRoute ApiRoute.Response requestPrinter : ApiRoute ApiRoute.Response
requestPrinter = requestPrinter =
ApiRoute.succeed ApiRoute.succeed