meteor-peerdb icon indicating copy to clipboard operation
meteor-peerdb copied to clipboard

JavaScript examples

Open juho opened this issue 10 years ago • 14 comments

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

juho avatar May 08 '15 19:05 juho

Yes, I am considering using PeerDB.

rclai avatar May 15 '15 13:05 rclai

Plain JS examples will be very usefull.

gogibob avatar Nov 15 '15 13:11 gogibob

+1

dpatte avatar Nov 15 '15 14:11 dpatte

+1

fabiodr avatar Feb 03 '16 19:02 fabiodr

I'm making an attempt to convert our Peerdb code to ES6 here: https://github.com/CommonGarden/Grow-IoT/pull/189

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

JakeHartnell avatar Jun 11 '16 21:06 JakeHartnell

+1

johngonzalez avatar Jul 13 '16 18:07 johngonzalez

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 avatar Jul 06 '17 21:07 janat08

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;
      }`

janat08 avatar Jul 07 '17 21:07 janat08

+1

Could you provide a simple example?

Is this library still being maintained as by Meteor 1.5?

gsc-dev avatar Jul 25 '17 06:07 gsc-dev

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.

mitar avatar Jul 25 '17 06:07 mitar

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 avatar Jul 26 '17 23:07 gsc-dev

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 avatar Jul 27 '17 20:07 gsc-dev

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 avatar Aug 01 '17 00:08 gsc-dev

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);
});

gsc-dev avatar Aug 01 '17 00:08 gsc-dev