Ember-restless with Ember 2.0 - javascript

Problems I have with ember are related to ember-restless module I would like to use instead of ember-data(I have completely removed data module from my project).
I am still learning ember so I am not sure if this has something with latest version, or with programming style, but I saw that in Ember 2.0 we would write
export default RL.Client.create({
adapter: App.RESTAdapter
});
instead of
App.Client = RL.Client.create({
adapter: App.RESTAdapter
});
but it seems that my client is then not recognised(if I write it in first way), as get request are made to localhost instead of url I specified in RESTAdapter class.
Second problem I have is that
import RL from 'ember-restless';
does not work for me, it says that module 'ember-restless' could not be found.
Any help would be appreciated, as I have been struggling with this for some time.
UPDATE
I changed importing syntax to following, and here's the situation:
import { Client } from 'ember-restless';
If a put this import in my model class, I am getting following error in js console:
Error: Could not find module 'ember-restless' imported from 'ember-test2/models/pol'
However, if I remove import from model class, leave adequate imports in RESTAdapter and Client definitions, there are no errors, but services are called on localhost:4200 instead on localhost:8080.
I will provide my definitions from js files here:
models/pol.js
import { RL } from 'ember-restless'; // imports entire library
var Pol = RL.Model.extend({
idPol: RL.attr('integer'),
naziv: RL.attr('string')
});
Pol.reopenClass({
resourceName: 'pol/e'
});
export default Pol;
adapters/application.js
import { RL } from 'ember-restless';
export default RL.RESTAdapter.create({
host: 'http://localhost:8080',
namespace: 'zareps'
});
adapters/client.js
import {RESTAdapter} from '../adapters/application';
import {Client} from 'ember-restless';
export default Client.create({
adapter: RESTAdapter
});
routes/list-pol.js
import Ember from 'ember';
import Pol from '../models/pol';
export default Ember.Route.extend({
model() {
return Pol.find();
}
});

Related

"Cannot access ModuleName before initialization" using import

I'm making an API for a web application, and I'm running into a weird problem when I try to import a module. I have a folder with a bunch of models used to get data from the database, and I have a folder named "global" with various modules used all over the project.
/
/api
/models
/Users.js
/Trainings.js
/TrainingsTypes.js
/TrainingsSubtypes.js
/global
/Functions.js
Some of the models import other models to check ID, get data, etc. I made a function in Functions.js that also needs some of the models to work. So basically, the import dependencies look like:
I must admit, this is a little crappy when showed like that. But here is my problem. As long as Functions.js doesn't import Users.js, everything is fine. The API works well and there's no crash at all. But, if I import Users.js in Functions.js, I immediatly get this error:
ReferenceError: Cannot access 'Users' before initialization
at file:///C:/Users/USERNAME/Desktop/project-api/global/Functions.js:30:10
at ModuleJob.run (internal/modules/esm/module_job.js:169:25)
at async Loader.import (internal/modules/esm/loader.js:177:24)
at async Object.loadESM (internal/process/esm_loader.js:68:5)
Here is the code of Functions.js (I put a comment to indicate line 30):
import check from "checkers";
import Users from "../api/models/Users.js";
import Trainings from "../api/models/Trainings.js";
import TrainingsTypes from "../api/models/TrainingsTypes.js";
import TrainingsSubtypes from "../api/models/TrainingsSubtypes.js";
/*****************************************************
* SQL Queries
*****************************************************/
export function fieldsToUpdate(fields) {...}
const fillers = {
"user": Users, // Line 30
"trainer": Users,
"type": TrainingsTypes,
"subtype": TrainingsSubtypes
};
export async function fillIDs(db, response) {...}
Moreover, the import itself doesn't cause problems. If I remove Users from the fillers object, there's still no crash. I've seen that might be a cyclic dependencies issue but some says that Node can handle this. I must add that I really need all my models in fillIDs() so I just can't remove all the import and I didn't want to copy/paste this code in every model. There must be a solution, but I need some help.
Have you any idea how to fix this?
Thanks
EDIT 1:
Users.js import these modules:
import bcrypt from "bcryptjs";
import generatePwd from "generate-password";
import { v4 as uuidv4 } from "uuid";
import check from "checkers";
import { fieldsToUpdate, fillIDs } from "../../global/Functions.js";
import { arrayToSerialComma } from "../../global/Converters.js";
import APIResp from "../../global/APIResp.js";
import Mailer from "../../global/Mailer.js";
import Genders from "./Genders.js";
import Roles from "./Roles.js";
import Tokens from "./Tokens.js";
import { Passwords } from "../../config/config.js";
EDIT 2:
Users.js is exported in this way:
const Users = {
isValid,
add,
logIn, getAll, getById, getByEmail, hasForgotPassword, getRolesOf,
update, updatePwd, passwordForgotten,
delete: del,
Trainers: {
getById: getTrainerById,
getAll: getAllTrainers
}
};
export default Users;
I managed to partially solve my problem. I've created a file in global exporting all the files in this folder and did the same for models.
// ROOT/global/global.js
export { default as APIResp } from "./APIResp.js";
export { default as SQLFunctions } from "./SQLFunctions.js";
export { default as Mailer } from "./Mailer.js";
export { default as ModuleConsole } from "./ModuleConsole.js";
// ROOT/api/models/models.js
export { default as Users } from "./Users.js";
export { default as Genders } from "./Genders.js";
export { default as Roles } from "./Roles.js";
export { default as Tokens } from "./Tokens.js";
export { default as Trainings } from "./Trainings.js";
export { default as TrainingsTypes } from "./TrainingsTypes.js";
export { default as TrainingsSubtypes } from "./TrainingsSubtypes.js";
I also removed some functions that was needed in both the front-end and back-end and moved them to an external module. I used madge to generate a dependency graph.
As we can see, it's not perfect yet. All the models files are actually in a big circular dependency but it's much cleaner than before and there are no more crashes.
This may have an impact on performance, and I have to be careful with that.
I mark this answer as correct for now, I may change it if someone else or I found something.

Ember, JSONAPIAdapter, JSONAPISerializer, findAll not available

Im building an Ember app "ember-cli": "2.4.3", sitting on Laravel/Lumen and cant seem to get the wires hooked up correctly. Im trying to also an API server JSON-API compliant, so I have access to alter the syntax if thats a problem.
If I remove the export default DS.JSONAPISERIALIZER, I get ember.debug.js:32116 TypeError: typeClass.eachTransformedAttribute is not a function
With it, I typically get Assertion Failed: You tried to load all records but your adapter does not implement findAll
If I call getJSON(...) from within the route, instead to calling the store for the data, it works perfectly, and displays to the view as expected.
I have tried other adapters but I think that being JSON-API compliant I need to use the JSONAPIADAPTER. Any help would be awesome.
application.js
import DS from "ember-data";
export default DS.JSONAPIAdapter.extend({
namespace: 'v1',
host: 'http://edu-api.app:8000',
});
export default DS.JSONAPISerializer.extend({
//in preparation of underscores in returned data
// keyForAttribute: function(attr) {
// return Ember.String.underscore(attr);
// },
// keyForRelationship: function(attr) {
// return Ember.String.underscore(attr);
// }
});
skill.js
import DS from 'ember-data';
var App = window.App = Ember.Application.extend();
var attr = DS.attr;
App.Skill = DS.Model.extend({
name: attr("string"),
desc: attr("string")
});
index.js
export default Ember.Route.extend({
model() {
//return this.store.findAll('skill'); //<- Assertion Failed: You tried to load all records but your adapter does not implement `findAll`
this.get('store').findAll('skill'); //<- Assertion Failed: You tried to load all records but your adapter does not implement `findAll`
//return Ember.$.getJSON('http://edu-api.app:8000/v1/skills'); //<- works, and properly displays data to view
}
});
I think you primary have problems understanding ember-cli.
First you don't put your adapter and serializer in the same file. Maybe use the generators to get a default file like ember generate serializer application.
Your application serializer goes to app/serializers/application.js, your adapter to app/adapters/application.js.
Next this line looks really really wrong:
var App = window.App = Ember.Application.extend();
This creates a new app, but you should do this only once in your app/app.js. Next you use a global export, what you should never do in an ember-cli app.
To specify your model you need to locate your file under models/skill.js. There you don't attach your new Model to a global exported App like App.Skill = DS.Model.extend({, but you export it as default export like export default DS.Model.extend({.
Your index.js looks right if its located under routes/.
I strongly recommend you to read more about the ember resolver, and the ember dependency injection framework which do all this magic for you. Also use the generators to get your files, it can help you to place your files right.

Ember access variable inside Mixin

import Ember from 'ember';
import myConst from '../utils/constants';
export default Ember.Mixin.create(myConst, {
getFieldId: function(productCode) {
console.log(myConst.MY_METHODS.FIELD_ID); //Not able to access this
}
});
My constants.js looks like
var myConst = {};
myConst.MY_METHODS = {
FIELD_ID: "fieldId"
};
export default myConst;
I am unable to access myConst inside the mixin. What am I doing wrong ?
I think you're confusing a couple of concepts here. In your example, myConst is a utility module that contains some default values, right? In that case, you don't want to mix it in to your mixin (which is what you're doing with Ember.Mixin.create(myConst, {...}). You should be doing something like this:
import Ember from 'ember';
import myConst from '<app-name>/utils/constants';
export default Ember.Mixin.create({
getFieldId: function(productCode) {
console.log(myConst.MY_METHODS.FIELD_ID);
}
});
If that doesn't work, it's likely something to do with your import path. I would start debugging by just console.loging myConst to make sure you have the intended object from your module.

Emberjs loadInitializer error

Not sure how to correct this error. I'm following along with this screencast https://www.youtube.com/watch?v=vLXGKNA4P_g and it appears that the update to Ember breaks functionality.
DEPRECATION: `lookup` was called on a Registry. The `initializer` API
no longer receives a container, and you should use an `instanceInitializer` to look up objects from the container.
See http://emberjs.com/guides/deprecations#toc_deprecate-access-to-
instances-in-initializers for more details.
I'm new to Ember and have found the https://github.com/emberjs/data/issues/3051 thread on github but I'm not quite sure how to fix this. This is my app.js file
import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
import config from './config/environment';
var App;
Ember.MODEL_FACTORY_INJECTIONS = true;
App = Ember.Application.extend({
modulePrefix: config.modulePrefix,
podModulePrefix: config.podModulePrefix,
Resolver: Resolver
});
loadInitializers(App, config.modulePrefix);
export default App;
Can someone explain how to make this compliant with the error? The documentation suggests this:
http://emberjs.com/deprecations/v1.x/#toc_deprecate-access-to-instances-in-initializers
But being new to Ember, I'm not sure what this means or how to implement it.

How do I access the Ember global 'App' variable in an Ember CLI application?

I am creating an Ember application using the Ember CLI. I have a view which invokes a component that I created. I am trying to access the global App variable to create my component and insert it into my layout.
The error: Uncaught ReferenceError: App is not defined
How do I fix this?
app.js
import Ember from 'ember';
import Resolver from 'ember/resolver';
import loadInitializers from 'ember/load-initializers';
Ember.MODEL_FACTORY_INJECTIONS = true;
var App = Ember.Application.extend({
modulePrefix: 'client-web', // TODO: loaded via config
Resolver: Resolver
});
loadInitializers(App, 'client-web');
export default App;
item-table.js (This is a view)
import Ember from 'ember';
export default Ember.View.extend({
templateName: 'item-table',
didInsertElement: function() {
// All my other code here
App.FreestyleChartComponent.create().appendTo($('#wp-chart td')); // This throws an error.
}
});
app/components/freestyle-chart.js
import Ember from 'ember';
export default Ember.Component.extend({
templateName: 'components/freestyle-chart',
didInsertElement: function() {
console.log('Inserted the component.');
}
});
I can think of two ways. The first is to put the App in the global scope manually.
var App = window.App = Ember.Application.extend();
The second is to import the App into your view:
import App from './path/to/app/file';
The latter is only possible if Ember CLI supports circular references. The official ES6 spec supports them but many transpilers don't (mine doesn't).
However, I don't think this is your root concern. For the most part, you shouldn't be accessing global variables in Ember CLI. Instead of placing the FreestyleChartComponent in the App namespace, why not just put it in a module and import it like any other module? Global variables are unavoidable (I experienced that today), but you should try to minimize them.
I do agree that you should not be accessing your app via the global namespace, however ember-cli actually does actually make you app a global with the name of your app being the name of the variable.
If you open /app/index.html in your ember-cli project you should see a script tag towards the bottom that looks like...
<script>
window.YourAppName = require('your-app-name/app')['default'].create(YourAppNameENV.APP);
</script>
in the above example YourAppName would be your app available as a global
Import the component that you want:
import FreestyleChartComponent from 'app_name/app/components/freestyle-chart';
There is no straight forward way to do this since Ember CLI wants you to use the public API and its given components rather than accessing the App instance directly.
Most solutions consist of making the App instance global, whereby this one does not. I did not test this, but I think this should work:
appname/utils/application.js
export default {
instance: null
};
appname/instance-initializers/application.js
import application from 'appname/utils/application';
export default {
name: 'app-initializer',
initialize: function (application) {
application.instance = application;
}
};
Now
import application from 'appname/utils/application';
and use application.instance in any file where you need the application instance.
Justed tested with Ember 3.7.
import App from 'app-name/app';
app-name has to be replace with the name of your app (I guess the one in package.json).

Categories