Cannot read property 'type' of undefined ember and firebase - google-cloud-firestore

I am trying to retrieve data from my firestore using ember.js and emberfire.
i have a simple movie database. All that is in it right now is 1 document but for some reason when i try and retrieve the data, i keep getting "Cannot read property 'type' of undefined"! i understand that this is a JSONAPI issue but nothing seems to fix it.
My Route:
import Route from '#ember/routing/route';
export default class MovieRoute extends Route {
async model() {
this.store.findAll('movies').then(function(movie) {
console.log(movie);
});
}
}
My Model:
import Model, { attr } from '#ember-data/model';
export default class MoviesModel extends Model {
#attr('string') title;
}
Now it was my understanding that the default JSONAPISerializer is the default one but i tried adding a serializer anyway and my error changes to: Assertion Failed: normalizeResponse must return a valid JSON API document.
My adapter:
import FirestoreAdapter from 'emberfire/adapters/firestore';
export default FirestoreAdapter.extend({
// Uncomment the following lines to enable offline persistence and multi-tab support
// enablePersistence: true,
// persistenceSettings: { synchronizeTabs: true },
});
My Serializer:
import JSONAPISerializer from '#ember-data/serializer/json-api';
export default class ApplicationSerializer extends JSONAPISerializer {}
it is also my understanding that the way the JSON is to be accepted is:
{
data {
type: 'movies',
id: 1,
attributes {
title: 'ghostbusters'
}
}
}
so i also created a new document in the firestore, following this same format. Still no luck.
Can anyone point me in the right direction as to how to get the correct data returning from the firestore?
**edited --
error message:

Related

How to create a custom class in NestJS and work with the instance of the class

I'm trying to create a helper class in NestJS which i can use in every file.
I tried to create the following class:
export class Logging {
public status: string;
private currentLog: Model<LogDocument>;
constructor(#InjectModel(Log.name) readonly log?: Model<LogDocument>) {
// Create a new log item when new instance of class is created
this.currentLog = new this.log({
title: 'New Log',
status: SyncStatusType.IN_PROGRESS,
startTime: new Date(),
});
}
public addCrashLog() {
// Update current log
}
public addSuccessLog() {
// Update current log
}
public finish() {
// Set status and update log
}
}
I want to be able to use this class in every other file and create a new instance of the class if necessary.
const newLog = new Logging();
newLog.addCrashLog();
....
Does someone have an idea how I can archive that with NestJS? Because I'm always having problems with dependency injection in NestJS when I'm trying to create a custom class.
First off, don't add the Logging class to any providers array, as that's what will tell Nest to create the instance. Next, if you're passing the values yourself, you don't need the #InjectModel() there's no need, as you're creating the class yourself. Lastly, just use the class as your example already shows, using the new keyword and handling the instantiation yourself. That should be all there is to it

Vuex ORM model constructor issue on insert

I have the following model:
import { Model } from '#vuex-orm/core'
export class User extends Model {
static entity = 'users'
static fields () {
return {
id: this.attr(null),
name: this.attr('')
}
}
}
and when I try to do this:
User.insert({
data: { id: 1, name: 'John' }
})
I get the following error:
Uncaught (in promise) TypeError: Class constructor User cannot be invoked without 'new'
Any idea what is the problem? This code is from the documentation, so I'm confused a little bit.
as I can see you are missing the registration of the model in the database at the beginning of the application.
You have to implement your vuex store with the corresponding plugin
EXAMPLE:
import Vue from 'vue'
import Vuex from 'vuex'
import VuexORM from '#vuex-orm/core'
import User from '#/models/User'
import Post from '#/models/Post'
Vue.use(Vuex)
// Create a new instance of Database.
const database = new VuexORM.Database()
// Register Models to Database.
database.register(User)
database.register(Post)
// Create Vuex Store and register database through Vuex ORM.
const store = new Vuex.Store({
plugins: [VuexORM.install(database)]
})
export default store
You now have good documentation in this regard
I hope I have helped you, greetings

"TypeError: this.types is not a function" when using "vuex-orm-decorators"

I'm trying to use the npm package 'vuex-orm-decorators' from https://github.com/scotley/vuex-orm-decorators#readme
When I try to insert into the DB, I get the error TypeError: this.types is not a function
Entity looks like this
import { Model } from "#vuex-orm/core";
import { NumberField, OrmModel, StringField } from "vuex-orm-decorators";
#OrmModel("races")
export default class Race extends Model {
#NumberField()
public ID!: number;
#StringField()
public Name!: string;
}
store looks like this:
import Vue from "vue";
import Vuex from "vuex";
import { ORMDatabase } from "vuex-orm-decorators";
Vue.use(Vuex);
export default new Vuex.Store({
.
.
.
plugins: [ORMDatabase.install()]
});
Also, maybe this is a clue.... in Vuex-Orm, this.setters is returning a value, but this.setters('all') is returning undefined.
/**
* Get all records.
*/
Model.all = function () {
return this.getters('all')();
};
From seeing the undefined basic fields and functions, it seems like the vuex-orm database isn't getting set up correctly. Any ideas?
I tried to create a stackoverflow tag for vuex-orm-decorators, but I'm not quite at 1500 rep yet, so I just tagged it as vuex-orm.
There is a small bug in vuex-orm-decorators package in the implementation of the types function defined in Vuex-ORM Single Table Inheritance docs.
I've created a fork in which I fixed this simple problem and created a pull request to update the original package.
Lastly, I've to point that from my tiny dive into this package that it isn't fully ready yet for table inheritance features built in Vuex-ORM but still is great for simple use cases.

Typescript - Get uninitialized properties after compilation

I am currently writing a wrapper around socket.io. Comming from a very object-oriented background, I want to implement the concept of Models in my framework/wrapper.
If you happen to know socket.io you might know that you get the data that is associated with an event as a parameter, now I have implemented a custom routing system where the handler of the route gets the data in an express.js like request object.
The idea is to have model classes that look something like this:
class XRequestModel
#v.String({ message: 'The username must be a string!' })
public userName: string;
}
And the route event might look something like this:
#RouteConfig({ route: '/something', model: XRequestModel })
class XEvent extends Route {
public on(req: Request<XRequestModel>, res: Response) {
// Handle Event
}
}
And to complete the example here is how the request object might look like:
class Request<T> {
public data: T;
}
Now generics in typescript are very limited since the type information is removed after compilation, I can not use the generic Request parameter ( which is the type of the model ) to get metadata from the model - Metadata, in this case, is the validation decorator. To overcome this issue I give a reference of the Model class to the RouteConfig of the RouteEvent, which is internally used and would allow me to create instances of the model, get the properties and so on...
The idea here is to give the handler of a route, a request object with pre-validated, typesafe data.
The thing holding me back from this, is the fact that unused properties, get removed after compilation by typescript, So I cannot get the metadata of the model. Initializing the class-property would solve this:
class XRequestModel
#v.String({ message: 'The username must be a string!' })
public userName: string = '';
}
But I think this makes for some very verbose syntax, and I dont want to force the user of this wrapper to init all the model properties.
An implementation side-note:
The user of the framework has to register the classes to a 'main' class and from there I can get the Route-class via decorator reflection.
When I try to get the properties of the model without initialized properties - First model example.
// Here the route.config.model refers to the model from the RouteConfig
Object.getOwnPropertyNames(new route.config.model());
>>> []
Here is what I get with initialized properties:
Object.getOwnPropertyNames(new route.config.model());
>>> [ 'userName' ]
Here a link to the GitHub repository: https://github.com/FetzenRndy/SRocket
Note that models are not implemented in this repo yet.
Basically, my question is: How can I get the properties of a class that has uninitialized properties after compilation.
The problem is that if no initialization happens, no code is emitted for the fields, so at runtime the field does not exist on the object until a value is assigned to it.
The simplest solution would be to initialize all fields even if you do so with just null :
class XRequestModel {
public userName: string = null;
public name: string = null;
}
var keys = Object.getOwnPropertyNames(new XRequestModel())
console.log(keys); // [ 'userName', 'name' ]
If this is not a workable solution for you, you can create a decorator that adds to a static field on the class and the walk up the prototype chain to get all fields:
function Prop(): PropertyDecorator {
return (target: Object, propertyKey: string): void => {
let props: string[]
if (target.hasOwnProperty("__props__")) {
props = (target as any)["__props__"];
} else {
props = (target as any)["__props__"] = [];
}
props.push(propertyKey);
};
}
class XRequestModelBase {
#Prop()
public baseName: string;
}
class XRequestModel extends XRequestModelBase {
#Prop()
public userName: string;
#Prop()
public name: string;
}
function getAllProps(cls: new (...args: any[]) => any) : string[] {
let result: string[] = [];
let prototype = cls.prototype;
while(prototype != null) {
let props: string[] = prototype["__props__"];
if(props){
result.push(...props);
}
prototype = Object.getPrototypeOf(prototype);
}
return result;
}
var keys = getAllProps(XRequestModel);
console.log(keys);

How to use type check Loopback / Fireloop PersistedModel

I'm using Fireloop with Loopback 3 and wanting to know how best to create typesafe hooks and remote methods using type checked PersistedModel and Validatable methods. I'd like to change the type of the constructor from ...
constructor(public model: any) { }
to ...
constructor(public model: SomeType) { }
I'd like to make PersistedModel calls like
this.model.count().then((n) => ...);
OR Validatable calls like:
model.validatesLengthOf('code', {
min: 6, max: 12, message: { min: 'too short', max: 'too long'}
});
The Fireloop examples like the one below only use any as type of this.model.
The firestarter model samples and Fireloop documentation were also of no use here.
I know that there is a type called ModelConstructor declared in the fireloop source tree under core/index.d.ts. This interface looks correct because it implements all the PersistedModel and Validatable methods but where is it published in npmjs? Is it already part of the Fireloop server SDK or do I need to npm install it? No idea.
import { Model } from '#mean-expert/model';
/**
* #module Account
* #description
* Write a useful Account Model description.
* Register hooks and remote methods within the
* Model Decorator
**/
#Model({
hooks: {
beforeSave: { name: 'before save', type: 'operation' }
},
remotes: {
myRemote: {
returns: { arg: 'result', type: 'array' },
http: { path: '/my-remote', verb: 'get' }
}
}
})
class Account {
// LoopBack model instance is injected in constructor
constructor(public model: any) { }
// Example Operation Hook
beforeSave(ctx: any, next: Function): void {
console.log('Account: Before Save', ctx.instance);
next();
}
// Example Remote Method
myRemote(next: Function): void {
this.model.find(next);
}
}
module.exports = Account;
Finially, I've also attempted to use the Loopback 3 Typescript definitions but hit more problems as the PersistedModel methods here are all declared as static so fail type checks and return Promise<T> | void. The later means you’re forced to type cast the result back to just Promise<T> so it seems like the type def authors have never actually used them. Is this a bug or am I missing something? Can't find any working examples to prove otherwise.
This is the server side API pain. Client side REST API for Fireloop is also undocumented (lots of example for Real-time API) but none for the REST api it's also supposed to include (just mentioned once in one issue). Would be nice to find it can all be type checked by Typescript.
I found that ModelConstructor validation methods were missing arguments like { message: 'my error message' } and methods like exists() returned Promise<any> instead of Promise<boolean>.
The type definitions in Loopback 3 Type definitions were more complete but were unusable unless fixed as described above.
In the end I used ..
# Used modified type defs from https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/loopback/index.d.ts
import { Validatable } from '../types/validatable';
# Fixed static methods and return types.
import { PersistedModel } from '../types/loopback';
constructor(public MyModel: Validatable | PersistedModel) {
let Model = MyModel as Validatable;
Model.validatesLengthOf('code', {
min: 6,
max: 80,
message: { min: 'too short', max: 'too long' } });
Model.validatesFormatOf('email',
{ with: this.reEmail,
message: 'invalid email address',
allowNull: false });
Model.validatesInclusionOf('role', {
in: RoleNames,
message: 'is not valid'
});
}
And in later methods ..
let Model = this.MyModel as PersistedModel;
// knows that isFound is boolean
Model.exists(code).then(isFound => { ... });