Created
August 20, 2022 12:41
-
-
Save kaermorchen/d77759473c135188a0004b84d2667374 to your computer and use it in GitHub Desktop.
Pass application instance into plain function in Ember.js projects
This file contains 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
///app/instance-initializers/application.js | |
export let instance; | |
export function initialize(owner) { | |
instance = owner; | |
} | |
export default { | |
initialize, | |
}; |
This file contains 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
//app/utils/query.js | |
import { instance } from '../instance-initializers/application'; | |
export default function query(path, options = {}) { | |
const session = instance.lookup('service:session'); | |
const { url, key } = session.data.authenticated; | |
const defaultHeaders = { 'Content-Type': 'application/json' }; | |
const headers = new Headers(Object.assign(defaultHeaders, options.headers)); | |
if (key) { | |
headers.append('Authorization', `Bearer ${key}`); | |
} | |
const req = new Request( | |
new URL(path, url), | |
Object.assign(options, { headers }) | |
); | |
return fetch(req).then((res) => res.json()); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment