How to use ember data "sub-models" when using pods - ember-data

I have a json like this:
{
id: 'some-id',
username: 'myusername',
name: {
first: 'first-name',
last: 'last-name'
}
}
I'm using pods with the following structure:
pods/
user/
model.js
serializer.js
name/
model.js
With user/model.js:
import DS from 'ember-data';
export default DS.Model.extend({
username: DS.attr('string'),
name: DS.belongsTo('?????????????', { async: false })
});
With user/name/model.js:
import DS from 'ember-data';
export default DS.Model.extend({
first: DS.attr('string'),
last: DS.attr('string')
});
With user/serializer.js:
import DS from 'ember-data';
export default DS.RESTSerializer.extend(DS.EmbeddedRecordsMixin, {
attrs: {
name: { embedded: 'always' }
}
});
My question is how do I refer the user/name/model in the belongsTo relation of user/model?

Related

vuejs router-link props send data

I want to send data from home component via book.vue router link, but I am getting an error. Where am I doing wrong?
Home.vue
export default {
data() {
return {
data: {
attributes: {
name: 'Jonh',
age: '25',
},
},
}
},
}
router/index.js:
const routes = [
{ path: '/Library/:id', name: 'Book', component: Book, props: true },
]
navigation:
:to="{ name: 'Book', params: { id: book.id}, props: { data: data.attributes} }"
Book.vue
export default {
props: {
id: {
type: Array,
required: true
}
}
}

How should i connect Schema models in Mongoose?

i want to make a User, Post and comment. connect them together and when i create a Post, it should be connected to one of my users. I don't know why i get an unusual error. Error:
ID cannot represent value: <Buffer 5e 9b f1 3e e9 49 61 38 fc 1a 6f 59>
these are all of my code so if you know whats my problem please help me fix it. Thanks
typeDefs:
import { gql } from 'apollo-server-express';
export const typeDefs = gql`
type User {
id: ID!
name: String!
email: String!
age: Int
posts: [Post!]!
comments: [Comment!]!
}
type Post {
id: ID!
title: String!
body: String!
published: Boolean!
author: User!
comments: [Comment!]!
}
type Comment {
id: ID!
text: String!
author: User!
post: Post!
}
`
UserSchema:
import mongoose, { mongo } from 'mongoose';
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
age: {
type: Number,
required: false
},
posts: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
],
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}
]
});
module.exports = mongoose.model('User',userSchema);
PostSchema:
import mongoose from 'mongoose';
const postSchema = new mongoose.Schema({
title: {
type: String,
required: true
},
body: {
type: String,
required: true
},
published: {
type: Boolean,
required: true
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
comments: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'Comment'
}
]
});
module.exports = mongoose.model('Post',postSchema);
CommentSchema:
import mongoose from 'mongoose';
const commentSchema = new mongoose.Schema({
text: {
type: String,
required: true
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'User'
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Post'
}
});
module.exports = mongoose.model('Comment',commentSchema);
Resolver:
import Users from './models/User';
import Posts from './models/Post';
import Comments from './models/Comment';
export const resolvers = {
Mutation: {
createUser: async (parent, args, context, info) => {
const user = new Users(args);
await user.save();
return user;
},
createPost: async (parent, { title, body, published, author }, context, info) => {
const user = await Users.findById(author);
if (!user) {
console.log("User not found")
}
console.log(user)
const post = new Posts({ title, body, published, author: user.id });
await post.save();
user.posts.push(post);
await user.save();
return post;
}
}
}
I have found the solution and you should use type: mongoose.Schema.Types.ObjectId and ref: 'Comment' and after that inside resolvers you should use population .

Vue Router Resets Global Data

Im trying to store user data globally using a Vue mixin: (main.js)
import Vue from 'vue';
import Resource from 'vue-resource'
import App from 'App';
import router from 'router/index';
Vue.use(Resource);
Vue.mixin({ //globals
delimiters: ["[[", "]]"],
http: {
root: 'http://127.0.0.1:5000/'
},
data: function() {
return {
user: {
authorized: false,
username: '',
password: '',
avatar: '',
entry: '',
skill: '',
arena: {
id: '',
start: false,
votes: '',
}
}
}
}
});
new Vue({
router: router,
el: '#app',
components: {
App
},
template: '<App/>'
});
I get the data from a login page just fine: (part of Login.vue)
import Vue from 'vue';
export default {
name: 'Login-Page',
data() {
return {
message: 'Hello Vue!'
}
},
methods: {
_make_basic_auth(user, pass) {
var tok = user + ':' + pass;
return "Basic " + btoa(tok);
},
_fetch_user(protocol) {
this.message = 'waiting...';
var auth = this._make_basic_auth(this.user.username, this.user.password);
Vue.http.headers.common['Authorization'] = auth;
this.$http[protocol]('api/u/' + this.user.username).then(response => {
this.message = "Success";
if (response.body.authorized) {
this.user = {...this.user, ...response.body};
setTimeout(() => {
this.$router.push({
name: 'Profile',
params: {
id: this.user.username
}
});
}, 1000);
}
}, response => {
this.message = response.body;
console.log(response.status + " " + response.body);
});
},
register() {
this._fetch_user('post');
},
login() {
this._fetch_user('get');
}
}
}
The data is just reset on redirect: (part of Main.vue)
import Profile from 'components/Profile'
export default {
name: "Main-Page",
methods: {
enterArena() {
this.$http.get('api/match').then(response => {
console.log(response.body);
this.user.arena = {...response.body, ...this.user.arena};
this.$router.push({
name: "Arena",
params: {'id': response.body.id}
});
}, error => {
console.log(error.status + " " + error.body);
});
}
},
created() {
console.log(this);
console.log(this.user);
if (!this.user.authorized)
this.$router.push({
name: "Login"
});
}
}
It was working before, here is my old repo https://github.com/Jugbot/Painter-Arena-Web-API/tree/6f3cd244ac17b54474c69bcf8339b5c9a2e28b45
I suspect that the error is from my new arrangement of components in my Router or flubbed this references.
index.js:
routes: [
{
path: '',
name: 'Main',
component: Main,
children: [
{
path: '/arena/:id',
name: 'Arena',
component: Arena
},
{
path: '/u/:id',
name: 'Profile',
component: Profile
}
]
},
{
path: '/login',
name: 'Login',
component: Login
},
{
path: '/404',
component: NotFound
},
{
path: '*',
redirect: '/404'
},
],
mode: 'hash'
Update:
Problem is still unsolved but as a workaround I just moved all mixin data to the $root instance and that managed to work.
I recommend you to use vuex for better state management. It is complicated to use mixins as a data storage for a vue application. Using vuex is convenient way to manipulate dynamic or static data across the application and will not be deleted in destroy hook upon exiting on a component.

Transpiled GraphQL with Babel is throwing error "Cannot call class as function"

I am trying to get running GraphQL server. I have simple schema in GraphQL
import {
GraphQLObjectType,
GraphQLInt,
GraphQLString,
GraphQLList,
GraphQLSchema
} from 'graphql'
import db from './models'
const user = new GraphQLObjectType({
name: "user",
description: 'This represents a user',
fields: () => {
return {
id: {
type: GraphQLInt,
resolve(user) {
return user.id
}
},
firstName: {
type: GraphQLString,
resole(user) {
return user.firstName
}
},
lastName: {
type: GraphQLString,
resole(user) {
return user.lastName
}
},
email: {
type: GraphQLString,
resole(user) {
return user.email
}
},
createdAt: {
type: GraphQLString,
resole(user) {
return user.createdAt
}
},
updatedAt: {
type: GraphQLString,
resole(user) => {
return user.updatedAt
}
}
}
}
})
const Query = new GraphQLObjectType({
name: 'Query',
description: 'This is root Query',
fields: () => {
return {
users: {
type: GraphQLList(user),
args: {
id: {
type: GraphQLInt
},
email: {
type: GraphQLString
}
},
resolve(root, args) {
return db.user.findAll({where: args})
}
}
}
}
})
const Schema = new GraphQLSchema({
query: Query
})
export default Schema
I am transpile it with babel into ES5, but every time when I try run it with express
import GraphHTTP from 'express-graphql'
import Schema from './schema'
app.use('/grapql', GraphHTTP({
schema: Schema,
pretty: true,
graphiql: true
}))
I am getting this error
\node_modules\graphql\type\definition.js:41
function _classCallCheck(instance, Constructor) { if (!instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }                                                             
TypeError: Cannot call a class as a function
I check it again and again if i have some typing error but i didnt find enything.
instead of type: GraphQLList(user) use type: new GraphQLList(user)
GraphQLList is a class and you have to create it's instance and use, but you have called it as a function.
const Query = new GraphQLObjectType({
name: 'Query',
description: 'This is root Query',
fields: () => {
return {
users: {
type: new GraphQLList(user),
args: {
id: {
type: GraphQLInt
},
email: {
type: GraphQLString
}
},
resolve(root, args) {
return db.user.findAll({where: args})
}
}
}
}
})

Why I'm not getting the params in activate method?

Working more on my previous example, I've got three classes. First the parent:
import { Router, RouterConfiguration } from 'aurelia-router';
export class MainPage
{
router: Router;
configureRouter(config: RouterConfiguration, router: Router)
{
config.map([
{ route: '', redirect: 'entities' },
{ route: 'entities', name: 'entities', moduleId: './entities/entities', nav: true, title: 'Entities' },
{ route: 'structures', name: 'structures', moduleId: './structures/structures', nav: true, title: 'Data Structures' },
]);
this.router = router;
}
}
Then the bigger brother:
import { Router, RouterConfiguration } from 'aurelia-router';
export class Entities
{
private router: Router;
configureRouter(config: RouterConfiguration, router: Router)
{
config.map([
{ route: '', name: 'entities-list', moduleId: './list', nav: true, title: 'Entities' },
{ route: ':name/events', name: 'entity-events', moduleId: './events', nav: true, title: 'Events' },
]);
this.router = router;
}
}
And finally the little sister:
import { inject, computedFrom } from 'aurelia-framework';
import { Services } from './services';
#inject(Services)
export class Event
{
private events = [];
constructor(private services : Services) {}
async attached(params, routeConfig)
{
debugger;
this.events = <any> await this.services.getEvents(params.name);
}
}
And I use the following method call to navigate to the little sister:
this.router.navigateToRoute('entity-events', { name: "Some Name" });
But when I get to the debugger breakpoint, there's no params, it's undefined. According to the documentation, there supposed to be an object passed to the activate method, containing the parameters of the route. Where did go wrong?
Use the activate method.
The params argument is passed to activate, not attached as you've written above.
async activate(params, routeConfig)
{
debugger;
this.events = <any> await this.services.getEvents(params.name);
}