js-data / js-data-rethinkdb

RethinkDB adapter for js-data. Main Site: http://js-data.io, API Reference Docs: http://api.js-data.io
MIT License
32 stars 5 forks source link

A way to support `unique` constraint in RethinkDB #29

Open menosprezzi opened 6 years ago

menosprezzi commented 6 years ago

I was using RethinkDB in my last project, with JSData because it offers a great and simple API. Like another DB's, rethinkdb doenst support unique constraints, and the developers comunity are adding a workaround to support this. My suggestion here is add a wrapper the create function with some like this:

    const adapter = new RethinkDBAdapter();
    (adapter as any).createFn = adapter.create;
    adapter.create = async function(mapper, props, opts) {
      for (const field of (mapper as any).schema.unique) {
        if (!(await (adapter as any).r.table(mapper.name).getAll(props[field], {index: field}).isEmpty()))
          throw new Error(`Unique constraint violated on field { ${field}: ${props[field]} }`);
      }
      return await (adapter as any).createFn(mapper, props, opts);
    };
crobinson42 commented 6 years ago

@menosprezzi contributions are welcome!