Coder Social home page Coder Social logo

spoonx / wetland Goto Github PK

View Code? Open in Web Editor NEW
258.0 14.0 19.0 2.82 MB

A Node.js ORM, mapping-based. Works with MySQL, PostgreSQL, SQLite and more.

Home Page: https://wetland.spoonx.org/

License: MIT License

JavaScript 0.23% TypeScript 99.77%
wetland orm typescript mysql postgres sqlite database nodejs

wetland's Introduction

Wetland

Build Status npm version Slack Status

Wetland is a modern object-relational mapper (ORM) for node.js based on the JPA-spec. It strikes a balance between ease and structure, allowing you to get started quickly, without losing flexibility or features.

New! Take a look at our wetland tutorial.

New! Wetland CLI now has its own repository. npm i -g wetland-cli.

New! Wetland has a nice entity generator. Let us do the heavy lifting. Repository can be found here.

Features

Wetland is based on the JPA-spec and therefore has some similarities to Hibernate and Doctrine. While some aspects of the ORM have been adapted to perform better in the Node.js environment and don't follow the specification to the letter for that reason, the JPA specification is a stable and well written specification that makes wetland structured and performant.

Some of the major features provided include:

  • Unit of work
  • Derived tables
  • Migrations
  • Transactions
  • Entity manager
  • Cascaded persists
  • Deep joins
  • Repositories
  • QueryBuilder
  • Entity mapping
  • Optimized state manager
  • Recipe based hydration
  • More...

Installation

To install wetland run the following command:

npm i --save wetland

Typings are provided by default for TypeScript users. No additional typings need installing.

Plugins / essentials

Compatibility

  • All operating systems
  • Node.js 8.0+

Gotchas

  • When using sqlite3, foreign keys are disabled (this is due to alter table not working for foreign keys with sqlite).

Usage

The following is a snippet to give you an idea what it's like to work with wetland. For a much more detailed explanation, head to the documentation..

const Wetland = require('wetland').Wetland;
const Foo     = require('./entity/foo').Foo;
const Bar     = require('./entity/foo').Bar;
const wetland = new Wetland({
  stores: {
    simple: {
      client    : 'mysql',
      connection: {
        user    : 'root',
        database: 'testdatabase'
      }
    }
  },
  entities: [Foo, Bar]
});

// Create the tables. Async process, only here as example.
// use .getSQL() (not async) in stead of apply (async) to get the queries.
let migrator = wetland.getMigrator().create();
migrator.apply().then(() => {});

// Get a manager scope. Call this method for every context (e.g. requests).
let manager = wetland.getManager();

// Get the repository for Foo
let repository = manager.getRepository(Foo);

// Get some results, and join.
repository.find({name: 'cake'}, {joins: ['candles', 'baker', 'baker.address']})
  .then(results => {
    // ...
  });

Entity example

Javascript

const { UserRepository } = require('../repository/UserRepository');

class User {
  static setMapping(mapping) {
    // Adds id, updatedAt and createdAt for your convenience.
    mapping.autoFields();

    mapping.entity({ repository: UserRepository })
    mapping.field('dateOfBirth', { type: 'datetime' });
  }
}

module.exports.User = User;

Typescript

import { entity, autoFields, field } from 'wetland';
import { UserRepository } from '../repository/UserRepository';

@entity({ repository: UserRepository })
@autoFields()
export class User {
  @field({ type: 'datetime' })
  public dateOfBirth: Date;
}

License

MIT

wetland's People

Contributors

elxris avatar ppvg avatar rawphs avatar rwoverdijk avatar s-hoff 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  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  avatar  avatar  avatar  avatar

wetland's Issues

cascade: ['remove']

Use getReference to watch to-be-deleted, to fetch children ids to-be-deleted, make reference again and so on to get a nice tree of to-be-deleted

Mapping helpers

Implement support for mapping helpers. Examples are:

  • autoPK (id, integer, auto increment)
  • autoCreatedAt (field createdAt datetime, preCreate)
  • autoUpdatedAt (field updatedAt datetime, prePersist)

These could use the event manager

Remove join value

On deleting Entity with relations, remove row from many table, too. Perhaps using join? Takes some experimenting I suppose.

Entity Meta

  • Use entity meta throughout application.
  • Identity Repositories either by scanning dirs, registering them manually in a config, or registering them manually on bootstrap.

Delete relations on delete entity

make persist smarter on delete (delete relations). This isn't the same as cascade delete, so don't let your mind go there again.
If the entity being deleted has cascade persist, we don't have to delete the relation for that specific property.

Auto migrations through snapshots

Implement snapshots for auto migrations. These snapshots persist the mapping and allow you to diff with the current mapping to auto-generate migrations.

Defaults for join config

Currently all options have to be provided. We can calculate joinColumns and such ourselves to leave less verbose configuration.

Support for relations

Support relations. This means deep nesting, query builder support, criteria, etc.

Criteria functions

(year(categories.createdAt) > 2015, 1, 2)

{year: {'categories.createdAt': {gt: 2015}}}

{if : [{year: {'categories.createdAt': {gt: 2015}}}, 1, 2]}

Config and Mapping

  • Move config to own component (number of conditionals is growing).
  • Move parts of mapping to separate classes in dir

Migrations

The first version will be pushed without migrations. Those have to be implemented (create and migrations up / down)

Foreign key support

Foreign key support for schemas has been implemented, but the unit of work has to be altered in order to support the right order of operations.

Extended configuration

Allow extended configuration of wetland. This includes setting defaults (default PK name for instance).

Orphan Removal

Implement Orphan Removal for one to one, one to many and many to many (privately owned relations).

Logging

// Passthrough all "start" and "query" events to the knex object.
client.on('start', function(obj) {
knex.emit('start', obj)
})

client.on('query', function(obj) {
knex.emit('query', obj)
})

client.on('query-error', function(err, obj) {
knex.emit('query-error', err, obj)
})

client.on('query-response', function(response, obj, builder) {
knex.emit('query-response', response, obj, builder)
})

One-sided manyToMany

Make it possible to only specify many to many on one side. We'll have to find a way to get the primary key on the other side. Easy when using references, only guessable when using strings (default to id).

Pre-flush error handling

On pre-flush, we calculate cascades and perform validation on data. When an exception gets thrown, we don't recover the unit of work's state from before the flush. This might be a problem when attempting to retry a persist after an exception. Although, that would still work unless you royally mess up the changes. This is only in the case of persist.

Error handling

Make a unified way of error handling. Easier to catch, easier to process.

Refresh logic

Change refresh logic to be configurable. Also apply refresh to freshly created entities.

wetland plugins

Create docs for wetland plugins. An example (and core plugin) will be wetland-node-traditional which allows you to use wetland like you would with other (different) orms:

let entity = new Entity();

entity.name = 'foo';

entity.save().then();

(use proxy plugins)

having

Add support for "having" in queries.

Class-based / context mapping

Implement class-based or context based mapping to make writing mappings easier. Currently mappings require a bit of boilerplate for es6 and lower. Decorators take this away.

An easy solution could be to return a "context" class when calling .field(), to eliminate the need for the property.

Event manager

Create an event manager that allows you to hook in at any given time

Dev-migrations

Setup auto-migrations for dev, so there's no need to run migrations between mapping changes.

dry-run migrations

Implement dry-run migrations for adapters that support transactions for DDL queries.

Mapping

@Mapping.Entity()
@Mapping.autoCreatedAt()
@Mapping.autoUpdatedAt()
@Mapping.noIdPk()
export class Foo {
  @Mapping.field('string')
  bar: string;

  @Mapping.field('text', {length: 400})
  bar2: string;
}

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.