Skip to content

Instantly share code, notes, and snippets.

@kaermorchen
Created August 20, 2022 12:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaermorchen/d77759473c135188a0004b84d2667374 to your computer and use it in GitHub Desktop.
Save kaermorchen/d77759473c135188a0004b84d2667374 to your computer and use it in GitHub Desktop.
Pass application instance into plain function in Ember.js projects
///app/instance-initializers/application.js
export let instance;
export function initialize(owner) {
instance = owner;
}
export default {
initialize,
};
//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