...
/Building a Server Endpoint for Autocomplete
Building a Server Endpoint for Autocomplete
Let's modify the server so that it returns data that's a little less hardcoded and more varied for a search engine example!
We'll cover the following...
Skeleton for suggestion stubs #
The server powering this search engine we’re building needs to respond with the actual suggestions. Let’s copy the mock server we built in the last lesson and modify it for this case.
// Serverconst endpoints = {"/": {"get": () => "hello world"}}// API libraryfunction getFunction(url, data, callback) {const domain = url.substring(0, url.indexOf("/"));const endpoint = url.substring(url.indexOf("/"), url.length);callback(endpoints[endpoint]["get"](data));}const api = {get: getFunction};
We need to add a new endpoint for autocomplete results. Let’s call it /autocomplete
, which will be an API endpoint that just responds with a list of results.
function getAutocompleteHandler(data) {const results = [];for (let i = 0; i < 10; i++) {results.push("asdf");}return results}const endpoints = {..."/autocomplete": {"get": getAutocompleteHandler}}
Will this work for our development purposes?
Yes, it gives a list of strings which is all we need
No, we want results that are prefixed with data we passed
No, we need more structured data to include the extra information in the edge case that there multiple results of the same string
B and C
Adding auxiliary information #
This server is lacking considering the feature set we’re aiming to include in our component. We want to be able to have varied results so that we can test that the bolding of individual letters is applied correctly and that different inputs lead to different results.
We also have an edge case where multiple results sharing the same string prefix include additional information. We don’t want to merely append the detail to the result ...