discourse/app/assets/javascripts/wizard/test/wizard-pretender.js.es6

105 lines
2.7 KiB
Plaintext
Raw Normal View History

2016-08-25 13:14:56 -04:00
// TODO: This file has some copied and pasted functions from `create-pretender` - would be good
// to centralize that code at some point.
function parsePostData(query) {
const result = {};
query.split("&").forEach(function(part) {
const item = part.split("=");
const firstSeg = decodeURIComponent(item[0]);
const m = /^([^\[]+)\[([^\]]+)\]/.exec(firstSeg);
2018-06-15 11:03:24 -04:00
const val = decodeURIComponent(item[1]).replace(/\+/g, " ");
2016-08-25 13:14:56 -04:00
if (m) {
result[m[1]] = result[m[1]] || {};
result[m[1]][m[2]] = val;
} else {
result[firstSeg] = val;
}
});
return result;
}
function response(code, obj) {
if (typeof code === "object") {
obj = code;
code = 200;
}
2018-06-15 11:03:24 -04:00
return [code, { "Content-Type": "application/json" }, obj];
2016-08-25 13:14:56 -04:00
}
export default function() {
const server = new Pretender(function() {
2018-06-15 11:03:24 -04:00
this.get("/wizard.json", () => {
2016-08-25 13:14:56 -04:00
return response(200, {
wizard: {
2018-06-15 11:03:24 -04:00
start: "hello-world",
completed: true,
2018-06-15 11:03:24 -04:00
steps: [
{
id: "hello-world",
title: "hello there",
index: 0,
description: "hello!",
fields: [
{
id: "full_name",
type: "text",
required: true,
description: "Your name"
}
],
next: "second-step"
},
{
id: "second-step",
title: "Second step",
2018-06-15 11:03:24 -04:00
index: 1,
fields: [{ id: "some-title", type: "text" }],
previous: "hello-world",
next: "last-step"
},
{
id: "last-step",
index: 2,
2018-06-15 11:03:24 -04:00
fields: [
{ id: "snack", type: "dropdown", required: true },
{ id: "theme-preview", type: "component" },
{ id: "an-image", type: "image" }
],
previous: "second-step"
2018-06-15 11:03:24 -04:00
}
]
2016-08-25 13:14:56 -04:00
}
});
});
2018-06-15 11:03:24 -04:00
this.put("/wizard/steps/:id", request => {
2016-08-25 13:14:56 -04:00
const body = parsePostData(request.requestBody);
if (body.fields.full_name === "Server Fail") {
return response(422, {
errors: [{ field: "full_name", description: "Invalid name" }]
});
} else {
return response(200, { success: true });
}
});
});
2018-06-15 11:03:24 -04:00
server.prepareBody = function(body) {
2016-08-25 13:14:56 -04:00
if (body && typeof body === "object") {
return JSON.stringify(body);
}
return body;
};
server.unhandledRequest = function(verb, path) {
2018-06-15 11:03:24 -04:00
const error =
"Unhandled request in test environment: " + path + " (" + verb + ")";
2016-08-25 13:14:56 -04:00
window.console.error(error);
throw error;
};
return server;
}