Giter Site home page Giter Site logo

aurelia-orm's Introduction

Archived

It was fun while it lasted, but we have to stop maintaining these repositories. We haven't used these projects for quite some time and maintaining them is becoming harder to do.

You deserve better, and for that reason we've decided to archive some repositories, which includes this one.

Feel free to fork and alter the repositories, and go forth making awesome stuff.

aurelia-orm

Build Status Known Vulnerabilities Gitter

Working with endpoints and client-side entities is unavoidable when doing API driven development. You end up writing a small wrapper for your XHRs / websocket events and putting your request methods in one place. Another option is just using Breeze, which is large, complex and not meant for most applications. Even though your endpoints are important, you still end up neglecting them.

Enter aurelia-orm. This module provides you with some useful and cool features, such as:

  • Entity definitions
  • Repositories
  • Associations
  • Validation
  • Type casting
  • Self-populating select element
  • And more

This makes it easier to focus on your application and organize your code.

This library is an unofficial plugin for the Aurelia platform. This library plays nice with the Sails.js framework.

Important note

We've simplified installation and usage! This plugin should now be installed using jspm i aurelia-orm or (for webpack) npm i aurelia-orm --save. Make sure you update all references to spoonx/aurelia-orm and spoonx/aurelia-api and remove the spoonx/ prefix (don't forget your config.js, package.json, imports and bundles).

Documentation

You can find usage examples and the documentation at aurelia-orm-doc.

The changelog provides you with information about important changes.

Uses

Used by

Installation

Aurelia-orm needs an installation of aurelia-api and aurelia-validation@^0.12.3.

Aurelia-Cli

Start by following the instructions for the dependencies of orm, aurelia-api and aurelia-view-manager. When done, resume with the other steps.

Run npm i aurelia-orm --save from your project root.

It also has submodules and makes use of get-prop. So, add following to the build.bundles.dependencies section of aurelia-project/aurelia.json.

"dependencies": [
  // ...
  "get-prop",
  {
    "name": "aurelia-orm",
    "path": "../node_modules/aurelia-orm/dist/amd",
    "main": "aurelia-orm",
    "resources": [
      "component/view/bootstrap/association-select.html",
      "component/view/bootstrap/paged.html"
    ]
  },
  {
    "name": "aurelia-validation",
    "path": "../node_modules/aurelia-validation/dist/amd",
    "main": "index"
  },
  // ...
],

Jspm

Run jspm i aurelia-orm npm:get-prop

And add following to the bundles.dist.aurelia.includes section of build/bundles.js:

  "get-prop",
  "aurelia-orm",
  "[aurelia-orm/**/*.js]",
  "aurelia-orm/**/*.html!text",

If the installation results in having forks, try resolving them by running:

jspm inspect --forks
jspm resolve --only registry:package-name@version

Webpack

Run npm i aurelia-orm --save from your project root.

Add aurelia-orm in the coreBundles.aurelia section of your webpack.config.js.

Typescript

Npm-based installations pick up the typings automatically. For Jspm-based installations, run typings i github:spoonx/aurelia-orm or add "aurelia-orm": "github:spoonx/aurelia-orm", to your typings.json and run typings i.

Example

Here's a snippet to give you an idea of what this module does.

entity/user.js

import {Entity, validatedResource} from 'aurelia-orm';
import {ValidationRules} from 'aurelia-validation';

@validatedResource('user')
export class UserEntity extends Entity {
  email    = null;
  password = null;

  constructor() {
    super();

    ValidationRules
      .ensure('email').required().email()
      .ensure('password').required().minLength(8).maxLength(20)
      .on(this);  
  }
}

page/some-view-model.js

import {EntityManager} from 'aurelia-orm';
import {inject} from 'aurelia-framework';

@inject(EntityManager)
export class Create {

  requestInFlight = false;

  constructor (entityManager) {
    this.entity = entityManager.getEntity('user');
  }

  create () {
    this.requestInFlight = true;

    this.entity.validate()
      .then(validateResults => {
        if (!validateResults[0].valid) {
          throw validateResults[0];
        }

        return this.entity.save();
      }).then(result => {
        this.requestInFlight = false;

        console.log('User created successfully');
      })
      .catch(error => {
        this.requestInFlight = false;
        // notify of the error?
      });
  }
}

Gotchas

When using this module, please keep in mind the following gotchas.

Bundling

When bundling your aurelia app, the bundler renames your modules (to save space). This is fine, but aurelia-orm allows you to add decorators without values, and uses the module name to set the value. For instance, @resource() would use the module's name to set the resource.

So keep in mind: When using aurelia-orm in a bundled application, you must specify a value for your decorators. For instance, @decorator('category').

Known hacks

  • The association-select always parses the placeholderText as html (t="[html]${placeholderText}") due a aurelia-i18n binding issue.

aurelia-orm's People

Contributors

bas080 avatar ctjhoa avatar cuddlebunny avatar doktordirk avatar go4cas avatar greenkeeperio-bot avatar gregoryagu avatar jeremyvergnas avatar jvkassi avatar kellyethridge avatar kukks avatar mroseboom avatar rwoverdijk avatar s-hoff avatar shauniarima avatar vmbindraban avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

aurelia-orm's Issues

association-select - Allow custom text for value=0 option

I would like to be able to override the default text value for the <option selected value="0">- Select a value -</option>. This will allow the developer to set custom text, e.g. "- Assign to user -", as opposed to the default "- Select a value -".

Custom actions

Unless there already is a way I'm not seeing, but would be nice to see the ability to add custom actions.

For example, if I wanted to add an authenticate() action to an entity.

manyAssociation

Add a manyAssociation decorator. This gives us more info on the entity supplied.

association-select - Allow hiding of value=0 option

I would like to be able to hide the default <option selected value="0">- Select a value -</option>. In certain cases it would be desirable NOT to display this option, e.g. for mandatory fields where the user should ALWAYS select a value.

warn if association not returned with an entity

Scenario:
Entitiy company has association Entity brand
the server however returns brandId with a company request. since those don.t match, it doesn.t work.
so either it may be made clearer in the docs or we log a warning if the association brand doesn.t apear on company servet requests

Update changed only

Currently, when saving an entity, the collection assocs all get added over again. No biggy, as the server side doesn't add twice, but a bit of a waste of resources.

This should be tackled, perhaps with the dirty check?

Thought about redux and GraphQL?

This is a pretty interesting development, though have you seen redux and GraphQL? The GraphQL technology is pretty cool and redux as a store is super simple.

Scott

Entity label

Add decorator to allow for entity label.

This label can be used as a key for i18n, too. This way, form generators and modals can automatically get the key (or label).

api/orm are not utilizing aurelia-authentication fetch client

i'm using spoonx libs aurelia-authentication, aurelia-api, aurelia-orm. upgraded to the latest versions today.

regardless of the order the 3 plugins are loaded in aurelia configuration, the fetch request is not including the "authorization" header that aurelia-authentication injects. this results in all ORM calls returning only 401 Unauthorized due to this.

regular calls with aurelia fetch client are working fine as expected with aurelia-authentication "authorization" header.

Error: A BindingLanguage must implement parseText(...)

Using aurelia-orm installing today we are getting this error. Changing the dependency for aurelia-templating to 1.2.1 it worked fine. So there is some incompatibility with 1.2.2.

DEBUG [templating] importing resources for http://localhost:9000/jspm_packages/npm/[email protected]/component/association-select.html []
aurelia-templating.js:692 Uncaught (in promise) Error: A BindingLanguage must implement parseText(...)
    at BindingLanguage.parseText (http://localhost:9000/jspm_packages/npm/[email protected]/aurelia-templating.js:692:13)
    at ViewCompiler._compileNode (http://localhost:9000/jspm_packages/npm/[email protected]/aurelia-templating.js:2008:79)
    at ViewCompiler._compileNode (http://localhost:9000/jspm_packages/npm/[email protected]/aurelia-templating.js:2028:33)
    at ViewCompiler.compile (http://localhost:9000/jspm_packages/npm/[email protected]/aurelia-templating.js:1985:12)
    at eval (http://localhost:9000/jspm_packages/npm/[email protected]/aurelia-templating.js:2615:49)

@transient not inherited

might be my current messed up TS version, but that version only works if i make my derived entitiy @transient as it's (in my messed up TS version at least) not inherited

How to handle nested resources

Hi guys,

I have a question regarding nested resources. I have an article with multiple comments. I get the article via GET /articles/{id} and the corresponding comments via GET /articles/{id}/comments (the id is retrieved via a URL param).

The first GET is no problem (entityManager.getRepository('article') and `find(params.id)). How would I handle the second GET? Right now, I am doing afind(params.id + '/comments')`` on the articles repo. This does not look correct so far, am I missing something here from the docs?

Now, the same for adding a comment. My resource is POST /articles/{id}/comments. How would I handle the dynamic param id in the comment entity?

Thank you for your help. Btw you are doing nice work here.

import * as entities unreliable

that might end up as having an es6Modules: true and getters in there ( aurelia-cli).-> crash on adding metadata

so, either:

  • don't use it
  • filter entities in registerEntities(entities) being of type Entity

HasAssociationValidationRule expects number keys.. Is it right?

Hi
having read the source code, I see that the HasAssociationValidationRule class setup a validation rule that checks for an id property, and that must be a number..

That means this plugin can't deal with string foreign keys?
I have a backend that uses GUID as primary/foreign keys (I'm not happy with this, but it uses RethinkDB, and it is a lot happier with guids than with integers).

Thanks!
P.

Update many assoc

When updating an entity (calling .save() or .update()) many relations don't get pushed as expected.

One fix for this, is to analyze the entity and set up actions to perform. Associations can be added through a series of /add calls.

Updating a collection won't delete the old existing items

When updating a collection (with association-select for example) it adds the selected items but doesn't remove the old existing ones.

It fires an OPTIONS request but not the DELETE request.

this.entity = this.repository.getPopulatedEntity(); // tags = [1,2,3,4]
this.entity.tags = [5, 6];
this.entity.save();

this.repository.getPopulatedEntity(); // tags = [1,2,3,4,5,6] (also in the DB)

EntitysetData({}) not working as expected.

@RWOverdijk

  setData(data) {
    Object.assign(this, data);

    return this;
  }

when data = {} , nothing happens. while i guess that is intended, wasn't clear enough in the docs. also a method to reset en entitiy is then needed (one can use EntityManager.getEntity('xy') though for this

convert isClean etc to getters

can't be used in views like that.
would be much easier if they'd be getters to enable disabled.bind="product.isClean"in views

Proposal: add an adapter layer between plugin operations and aurelia-api

Scenario

I have several APIs I want to call in an uniform manner, and I want to use aurelia-orm as the only data access layer in my app.
For my APIs I could use a combination of well-known server libraries (like loopback), third-party ones, and custom written (maybe legacy) used among my company.

Proposal

aurelia-orm will provide a way to configure a specific adapter for a repository, that will come from external plugins that I load beforehand.
For example there could be an aurelia-orm-loopback plugin that provides an adapter for loopback based APIs. A developer should be able to write a custom adapter directly inside its app to deal with a custom API.

There are several features that aurelia-orm currently does not provide that should be added for completeness, like the ability to shape results on GET operations (for example a common approach is to support a query parameter like expand=prop1,prop2.subprop1).

I plan to write my next API with loopback, but currently I can't say if I'll be able to implement the client-side part as an adapter for aurelia-orm (I just started to read the docs, so I don't have the necessary background yet).

Waiting for votes on this..

getFlat() should call public asObject() and not internal _asObject()

I just discovered that the private getFlat method, used by the markClean public method, does not call the asObject public method, that I currently override, but the private/internal _asObject method.

This violates the inheritance contract, as someone (like me for example ;) ) can override the base asObject method to remove some harmful properties, that in my case cause circular ref errors on JSON.stringify.

decorator @type

causes dirty checking of the property as it makes it non-configurable

Make Repository.findPath relative to resource

Hi
maybe it's only me, but when I program against a Repository instance, I'd expect every operation bounded to the resource path. If I don't want that, I can simply program against the Rest endpoint..

I need the findPath method, because my endpoint follows a (very common) REST structure where ids are in the path: /categories/id
If there's another clean way to GET a resource by altering the path, then discard the following.

The findPath method on Repository feels wrong to me. It simply forwards the path to the underlying Rest endpoint, without prefixing resource path:

var findQuery = this.getTransport().find(path, criteria);

but it can be changed to

var findQuery = this.getTransport().find(this.resource + path, criteria);

and change the find method accordingly:

    Repository.prototype.find = function find(criteria, raw) {
      return this.findPath('', criteria, raw);
    };

Then I can use the findPath method like repo.findPath('/id')

How to display validation messages during inputing forms

I might be missing something, but how do I achieve the same functionality as with the pure aurelia-validation? I want to show the user real-time input validation messages, not only validate during submiting the form. I'm looking for a solution that doesn't require to duplicate code (such as one set of validation rules in the entity and another one strictly for showing messages inside the form) Let's say I have a customer entity:
@validatedResource('customers')
export class Customer extends Entity {
@ensure(it => it.isNotEmpty().hasLengthBetween(1, 20))
name = null;
}

And somewhere in the app I'm using it in a form:
newcustomer.html
<button click.delegate="save()" >
Save </button>
<form validate.bind="validation" role="form">
<div class="form-group">
<label>Name</label>
<input type="text" placeholder="Name and Surname" class="form-control"
value.bind="customer.name" />
</div>
</form>
newcustomer.js
....
@inject(EntityManager)
export class newcustomer {
constructor(entityManager) {
this.customersRepository = entityManager.getRepository('customers');
this.customer = entityManager.getEntity('customer')
}
save() {
this.customer.getValidation().validate().then( () => {
console.log("I updated"+ this.customer.name);
return this.customer.save()
} )
};
By default aurelia-validation would attach messages to the such as is required or length has to be between x and y.
Thanks for any help!

Make deleting the id field before an update request optional

I usually design my PUT api like so:

[HttpPut]
public async Task<JsonResult> Put([FromBody] T item) {
    // ...
}

but after seeing the HTTP traffic from this plugin I had to change it to:

[HttpPut("{id}")]
public async Task<JsonResult> Put([FromRoute] Guid id, [FromBody] T item) {
    item.Id = id;
    // ...
}

See this thread if more context is needed: SpoonX/aurelia-api#151

Collection state

Currently, there's a bug with collection associations that causes the isClean() to give false positives when the entity in question has new, not persisted children. The problem lies in the way we check the entity's state. We create a flat representation of the collections (by id) obviously not including new children.

We could change this, and just include null values for new entities, but then the saveCollections method has to be altered, too (which will remove all the flexibility currently implemented).

I already have a pretty good idea how I want to solve this, and will come with a PR somewhere this week.

Read only

Add read only properties, omitting any changes made to the entity on save, unless forced.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.