Created
March 24, 2017 16:05
-
-
Save fsmanuel/3b70467ad6083db1d3b6a4797dcb2f89 to your computer and use it in GitHub Desktop.
Mirage queryParams support (JSON:API filter, page and sort)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function applyQueryParams(collection, queryParams) { | |
let qp = { | |
filter: {}, | |
page: {}, | |
sort: '' | |
}; | |
Object.keys(queryParams) | |
.reduce((data, key) => { | |
let matches = key.match(/(.*)\[(.*)\]$/); | |
if (matches) { | |
data[matches[1]][matches[2]] = queryParams[key]; | |
} else { | |
data[key] = queryParams[key]; | |
} | |
return data; | |
}, qp); | |
if (qp.filter) { | |
collection = collection.where(qp.filter); | |
} else { | |
collection = collection.all(); | |
} | |
// TODO: Add sort | |
if (qp.page) { | |
let start = (qp.page.number * qp.page.size) - qp.page.size; | |
collection = collection.slice(start, qp.page.size); | |
} | |
return collection; | |
} | |
export function testConfig() { | |
[ | |
'users' | |
].forEach((resource) => { | |
this.get(`/${resource}`, (schema, { queryParams }) => { | |
return applyQueryParams(schema[resource.camelize()], queryParams); | |
}); | |
this.get(`/${resource}/:id`, (schema, request) => { | |
return schema[resource.camelize()].find(request.params.id); | |
}); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment