Show HN: Write ajax requests with template literals
github.com
github.com
let response = await request`
url: https://api.myapp.com/register
method: POST
body: ${body}
headers: ${{
Authorization: 'Bearer: token'
}}
`
better than: let response = await request({
url: 'https://api.myapp.com/register',
method: 'POST',
body: body,
headers: {
Authorization: 'Bearer: token'
}
)
Perhaps it's just personal style, but the readability of both is similar and it feels like you've created a subset of a JSON or YAML parser that isn't as bulletproof / flexible.I did enjoy the example of how template literals are parsed under the hood.
partial:
const twitter = {
register: partial`
url: https://api.twitter.com/register,
method: POST
`
}
twitter.register`
body: ${{
email: 'test@test.com',
password: 'Tester'
}}
`
Without template literals: const twitter = {
register: {
url: 'https://api.myapp.com/register',
method: 'POST',
}
}
let response = await request({
...twitter.register,
body: body,
}) const twitter = {
register: function(opts){
return request({
url: '...',
method: 'POST',
...opts
});
}
}
const resp = await twitter.register({ body });
EDIT: made it even more concise! -- back to real work :/