Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JavaScript examples #30

Open
juho opened this issue May 8, 2015 · 14 comments
Open

JavaScript examples #30

juho opened this issue May 8, 2015 · 14 comments

Comments

@juho
Copy link

juho commented May 8, 2015

Coffeescript examples are cool, but still a little esoteric. Please consider providing plain JS examples instead.

@rclai
Copy link

rclai commented May 15, 2015

Yes, I am considering using PeerDB.

@gogibob
Copy link

gogibob commented Nov 15, 2015

Plain JS examples will be very usefull.

@dpatte
Copy link

dpatte commented Nov 15, 2015

+1

1 similar comment
@fabiodr
Copy link

fabiodr commented Feb 3, 2016

+1

@JakeHartnell
Copy link

I'm making an attempt to convert our Peerdb code to ES6 here: CommonGarden/Grow-IoT#189

Haven't got it working quite yet, but perhaps it's a start? Anyone made any individual progress on this?

@johngonzalez
Copy link

+1

@janat08
Copy link

janat08 commented Jul 6, 2017

So maybe a simple post here with reference to API and it's counterpart in js would suffice. There's decaffeinate, but it looks dodgy judging by jake's commit for translation.
@ is this, that should be inside the static property called initClass according to it.

@janat08
Copy link

janat08 commented Jul 7, 2017

Or I suppose that given that you're basically defining a schema, CS is way to go. If running generator use "`"/backtick for generator property value of a function that you define with JS:

    generators: `generators => {
        generators.slug = this.GeneratedField('self', ['title'], function(fields) {
          if (!fields.title) {
            return [fields._id, undefined];
          } else {
            return [fields._id, `prefix-${ fields.title.toLowerCase() }-suffix`];
          }
      });
        return generators;
      }`

@gsc-dev
Copy link

gsc-dev commented Jul 25, 2017

+1

Could you provide a simple example?

Is this library still being maintained as by Meteor 1.5?

@mitar
Copy link
Member

mitar commented Jul 25, 2017

It is. It is so stable that there is no need to do much. :-)

Sadly, I do not have time at the moment to provide examples.

@gsc-dev
Copy link

gsc-dev commented Jul 26, 2017

Tried the following but I couldn't understand how to add the ReferenceFields as the entire Person object is inserted in the collection and the Post embedded document doesn't update when displayName is updated in the Person instance.

// Model.js
export class Model extends Document {  // eslint-disable-line

  // Constructor
  static initClass() {
    this.Meta({
      abstract: true,
    });
  }

  // Class methods
  static verboseName() {
    return this.Meta._name.toLowerCase();
  }
}
Model.initClass();


export class Person extends Model {

  static initClass() {
    this.Meta({
      name: 'Person',
    });
  }

  fullName = () => {
    return this.name + ' ' + this.surname;
  }

}
Person.initClass();


export class Post extends Model {

  // Constructor
  static initClass() {
    this.Meta({
      name: 'Post',
      fields: () => {
        return {
          author: this.ReferenceField(Person, ['username', 'displayName']),
          subscribers: [this.ReferenceField(Person)],
          reviewers: [this.ReferenceField(Person, ['username', 'displayName'])],
        }
      },
    });
  }

  fullName = () => {
    return this.name + ' ' + this.surname;
  }

}
Post.initClass();

// index.js

import { Person, Post} from './Model.js';

console.log('\n\n=== Inserting Person. ===.\n');

const newPerson = new Person();
newPerson.name = 'Jane';
newPerson.surname = 'Brown';
newPerson.username = 'jane.brown';
newPerson.displayName = 'JJ';

Person.documents.remove({});
let personId = Person.documents.insert(newPerson);
let person =  Person.documents.findOne(personId);

console.log('Person: ', person);
console.log('Person - fullName: ', person.fullName('name'));
console.log('Person - updateUpdatedAt: ', person.updateUpdatedAt);


console.log('\n\n=== Inserting Post... ===\n');

const newPost = new Post();
newPost.title = '10 best restaurants in London';
newPost.author = person;

Post.documents.remove({});
let postId = Post.documents.insert({newPost});
let post =  Post.documents.findOne(postId);
console.log('post: ', post);


console.log('\n\n=== Updating Person.. ===\n');

Person.documents.update({_id: personId}, {displayName: 'Deanna Troi-Riker'});
person =  Person.documents.findOne(personId);
console.log('Person: ', person);

post =  Post.documents.findOne(postId);
console.log('\nPost: ', post);

Results:

import { Person, Post} from './Model.js';

console.log('\n\n=== Inserting Person. ===.\n');

const newPerson = new Person();
newPerson.name = 'Jane';
newPerson.surname = 'Brown';
newPerson.username = 'jane.brown';
newPerson.displayName = 'JJ';

Person.documents.remove({});
let personId = Person.documents.insert(newPerson);
let person =  Person.documents.findOne(personId);

console.log('Person: ', person);
console.log('Person - fullName: ', person.fullName('name'));
console.log('Person - updateUpdatedAt: ', person.updateUpdatedAt);


console.log('\n\n=== Inserting Post... ===\n');

const newPost = new Post();
newPost.title = '10 best restaurants in London';
newPost.author = person;

Post.documents.remove({});
let postId = Post.documents.insert({newPost});
let post =  Post.documents.findOne(postId);
console.log('post: ', post);


console.log('\n\n=== Updating Person.. ===\n');

Person.documents.update({_id: personId}, {displayName: 'Deanna Troi-Riker'});
person =  Person.documents.findOne(personId);
console.log('Person: ', person);

post =  Post.documents.findOne(postId);
console.log('\nPost: ', post);

@gsc-dev
Copy link

gsc-dev commented Jul 27, 2017

Hi @mitar would you be able to clarify how to insert the references in the collections?

I couldn't make it work even in coffescript. The references don't get updated!

class Person extends Document
  @Meta
    name: 'Person'

class Post extends Document
  @Meta
    name: 'Post'
    fields: =>
      # We can reference other document
      author: @ReferenceField Person, ['username', 'displayName']
      # Or an array of documents
      subscribers: [@ReferenceField Person]
      reviewers: [@ReferenceField Person, ['username', 'displayName']]
console.log '\n\nTESTINNG PEERDB'

Person.documents.remove
Post.documents.remove

personId = Person.documents.insert
    name: 'Jane'
    surname: 'Brown'
    username: 'jane.brown'
    displayName: 'JJ'
console.log '\n\ninserted person: ', personId
person = Person.documents.findOne(personId)
console.log person

postId = Post.documents.insert
    title: 'My first post'
    author: person
    # subscribers: [person]
    # reviewers: [person]
console.log '\n\ninserted post: ', postId
post = Post.documents.findOne(postId)
console.log post


console.log '\n\nupdated person displayname: '
Person.documents.update person._id,
  $set:
    displayName: 'Deanna Troi-Riker'

person = Person.documents.findOne(personId)
post = Post.documents.findOne(postId)
console.log person
console.log post

Results:

I20170727-21:53:37.152(1)? TESTINNG PEERDB
I20170727-21:53:37.157(1)?
I20170727-21:53:37.158(1)?
I20170727-21:53:37.158(1)? inserted person:  YLLhtQ5kXCTN5BwdF
I20170727-21:53:37.162(1)? Person {
I20170727-21:53:37.163(1)?   _id: 'YLLhtQ5kXCTN5BwdF',
I20170727-21:53:37.163(1)?   name: 'Jane',
I20170727-21:53:37.163(1)?   surname: 'Brown',
I20170727-21:53:37.163(1)?   username: 'jane.brown',
I20170727-21:53:37.164(1)?   displayName: 'JJ' }
I20170727-21:53:37.165(1)?
I20170727-21:53:37.165(1)?
I20170727-21:53:37.165(1)? inserted post:  aLTtt9wdXtf6Xyf3X
I20170727-21:53:37.166(1)? Post {
I20170727-21:53:37.166(1)?   _id: 'aLTtt9wdXtf6Xyf3X',
I20170727-21:53:37.166(1)?   title: 'My first post',
I20170727-21:53:37.167(1)?   author:
I20170727-21:53:37.167(1)?    Person {
I20170727-21:53:37.167(1)?      _id: 'YLLhtQ5kXCTN5BwdF',
I20170727-21:53:37.167(1)?      name: 'Jane',
I20170727-21:53:37.168(1)?      surname: 'Brown',
I20170727-21:53:37.168(1)?      username: 'jane.brown',
I20170727-21:53:37.168(1)?      displayName: 'JJ' } }
I20170727-21:53:37.169(1)?
I20170727-21:53:37.169(1)?
I20170727-21:53:37.169(1)? updated person displayname to Deanna Troi-Riker':
I20170727-21:53:37.170(1)? Person {
I20170727-21:53:37.170(1)?   _id: 'YLLhtQ5kXCTN5BwdF',
I20170727-21:53:37.171(1)?   name: 'Jane',
I20170727-21:53:37.171(1)?   surname: 'Brown',
I20170727-21:53:37.171(1)?   username: 'jane.brown',
I20170727-21:53:37.171(1)?   displayName: 'Deanna Troi-Riker' }
I20170727-21:53:37.172(1)? Post {
I20170727-21:53:37.172(1)?   _id: 'aLTtt9wdXtf6Xyf3X',
I20170727-21:53:37.172(1)?   title: 'My first post',
I20170727-21:53:37.173(1)?   author:
I20170727-21:53:37.173(1)?    Person {
I20170727-21:53:37.173(1)?      _id: 'YLLhtQ5kXCTN5BwdF',
I20170727-21:53:37.173(1)?      name: 'Jane',
I20170727-21:53:37.174(1)?      surname: 'Brown',
I20170727-21:53:37.174(1)?      username: 'jane.brown',
I20170727-21:53:37.174(1)?      displayName: 'JJ' } }
I20170727-21:53:37.197(1) (lib.coffee:1413) Enabling observers...
I20170727-21:53:37.237(1) (lib.coffee:1417) Done

@gsc-dev
Copy link

gsc-dev commented Aug 1, 2017

Hi @mitar I finally came up with a working example in ES6 with:

  • extends
  • class methods
  • instance methods
  • reference fields
  • generators
  • triggers
/* eslint new-cap: 0 */

const differ = require('deep-object-diff').diff;

export class Model extends Document {  // eslint-disable-line

  // Constructor
  static initClass() {
    this.Meta({
      abstract: true,
    });
  }

  // Class methods
  static verboseName = () => this.Meta._name.toLowerCase();
}
Model.initClass();


export class Person extends Model {

  static initClass() {
    const triggers = () => ({
      updateUpdatedAt: this.Trigger(['username', 'displayName'], (updated, current) => {
        if (updated && updated._id) {
          this.documents.update(updated._id, {
            $set: {
              diff: differ(current, updated),
              updatedAt: new Date(),
            },
          });
        }
      }),
    });

    this.Meta({
      name: 'Person',
      triggers,
    });
  }

  fullName = () => `${this.name} ${this.surname}`;
}
Person.initClass();


export class Post extends Model {

  // Constructor
  static initClass() {
    const message = this.GeneratedField('self', ['title'], (document) => {
      if (document.length <= 1) return [];
      return [
        document._id,
        `new post: ${document.title}!`,
      ];
    });

    const fields = () => ({
      author: this.ReferenceField(Person, ['username', 'displayName']),
      subscribers: [this.ReferenceField(Person)],
      reviewers: [this.ReferenceField(Person, ['username', 'displayName'])],
      message,
    });

    this.Meta({
      name: 'Post',
      fields,
    });
  }
}
Post.initClass();

@gsc-dev
Copy link

gsc-dev commented Aug 1, 2017

And this is how to test:

Document.startup() is required so the functionality can be started after PeerDB observers are initialised.
A setTimout is also needed so the effect of the observers can be seen on the tests:

import { Meteor } from 'meteor/meteor';

import { Person, Post } from './Model.js';

Document.startup(() => { // eslint-disable-line
  Person.documents.remove({});
  Post.documents.remove({});

  console.log('\n\n=== Inserting Person. ===.\n');

  const personId = Person.documents.insert({
    name: 'Jane',
    surname: 'Brown',
    username: 'jane.brown',
    displayName: 'JJ',
  });

  let person = Person.documents.findOne(personId);
  console.log('Person: ', person);
  console.log('Person - fullName: ', person.fullName('name'));
  console.log('Person - updateUpdatedAt: ', person.updateUpdatedAt);


  console.log('\n\n=== Inserting Post... ===\n');

  const postId = Post.documents.insert({
    title: '10 best restaurants in London',
    author: person,
  });

  let post = Post.documents.findOne(postId);
  console.log('post: ', post);


  console.log('\n\n=== Updating Person.. ===\n');

  Person.documents.update({ _id: personId }, {
    username: 'Janny',
    displayName: 'Deanna Troi-Riker',
  });

  Meteor.setTimeout(() => {
    person = Person.documents.findOne(personId);
    console.log('Person: ', person);

    post = Post.documents.findOne(postId);
    console.log('\nPost: ', post);
  }, 300);
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

10 participants