bs-crud-functors

7.1.2 • Public • Published

NPM pipeline status coverage report

bs-crud-functors

ReasonML model and query generator for CRUD actions based upon bs-sql-common and bs-sql-composer.

Why?

This is a SQL wrapper that provides many convenience features and a "light" ORM interface that uses plain SQL as the underlying language. Currently it is only compatible with the [bs-mysql2] client.

How do I install it?

Inside of a BuckleScript project:

yarn add @glennsl/bs-json bs-crud-functors bs-mysql2 bs-node-debug bs-sql-common bs-sql-composer

Then add @glennsl/bs-json, bs-crud-functors, bs-mysql2, bs-node-debug, bs-sql-common and bs-sql-composer to your bs-dependencies in bsconfig.json:

{
  "bs-dependencies": [
    "@glennsl/bs-json",
    "bs-crud-functors",
    "bs-mysql2",
    "bs-node-debug",
    "bs-sql-common",
    "bs-sql-composer"
  ]
}

How do I use it?

General Usage

The way you should access modules in CrudFunctors is as follows:

CrudFunctors.<Module>

Of course you can always directly call the internal files, namespaced with CrudFunctors_, but that is not recommended since these files are implementation details.

Using the Factory Model.

Below are the requirements necessary to use the FactoryModel. Each requirement is documented with examples below. The requirements include: creating the connection, creating the config, and creating the model.

Creating the Connection

module Sql = SqlCommon.Make_sql(MySql2);
module CrudFunctorImpl = CrudFunctor.Make(Sql)
 
let conn = Sql.connect(
  ~host="127.0.0.1",
  ~port=3306,
  ~user="root",
  ~database="example",
  ()
);

Creating the Config

Creating the Config is quite simple, below is a brief explanation for each field in the Config:

  • t: the record type that will be mapped to
  • table: the name of the database table
  • decoder: a function to map the query response to t
  • base: the base query for the model, try to keep this as thin as possible (i.e. minimal where clauses, etc.)
let table = "animal";
 
type animal = {
  id: int,
  type_: string,
  deleted: int,
};
 
module Config = {
  type t = animal;
  let table = table;
  let decoder = json =>
    Json.Decode.{
      id: field("id", int, json),
      type_: field("type_", string, json),
      deleted: field("deleted", int, json),
    };
  let base =
    SqlComposer.Select.(
      select
      |> field({j|$table.`id`|j})
      |> field({j|$table.`type_`|j})
      |> field({j|$table.`deleted`|j})
      |> order_by(`Desc({j|$table.`id`|j}))
    );
};

Creating the Model

Creating the model is quite simple once the Config is setup:

module Model = CrudFunctorImpl.Model.Make(Config);

Usage Examples

Below are a few examples on how to use the model, refer to the documentation below for the full list of functions/methods:

Model.Create.one(
  type_ => Json.Encode.([ ("type_", string @@ type_) ] |. object_),
  "my cat",
  conn
)
|. Future.mapOk(maybeCat =>
  switch(maybeCat) {
  | Some(cat) => Js.log2("Your New Cat: ", cat)
  | None => Js.log("Oh the noes, we lost your cat")
  }
)
|. Future.flatMapError(error => Js.Console.error(error))
|. ignore;
 
Model.Read.where(
  (base) => base |. SqlComposer.Select.where({j|AND $table.type_ = ?|j}),
  Json.Encode.([| string @@ "cat" |]),
  conn
)
|. Future.mapOk(cats => Js.log2("Your Cats:", cats))
|. Future.flatMapError(error => Js.Console.error(error))
|. ignore;

Creating an ID can be a pain-point, but it's abstracted away to ensure proper handling and formatting.

let id  = 42 |. Json.Encode.int |. string_of_int |. CrudFunctorImpl.Id.fromJson;
Model.Read.one_by_id(id, db)
|. Future.mapOk(maybeCat =>
  switch(maybeCat) {
  | Some(cat) => Js.log2("Your Cat: ", cat)
  | None => Js.log("Oh the noes, we couldn't find your cat")
  }
)
|. Future.flatMapError(error => Js.Console.error(error))
|. ignore;

Note: you will notice that some methods will return Result.Ok(None), this means that the row(s) were altered successfully but when an attempt to fetch the same row(s) was made the operation failed; this is because the Model's base query filters out the row(s) after update.

What's missing?

Everything not checked...

  • Query Interface
    • (raw) Raw SQL query
    • (rawInsert) Raw SQL insert
    • (rawUpdate) Raw SQL update
    • INSERT
      • (insertOne) basic wrapper
      • (insertBatch) basic wrapper
    • UPDATE
      • (updateOneById) Basic wrapper using the id column - must fit PrimaryId interface
      • (updateWhereParams) with the ObjectHash interface
      • (incrementOneById) increment an integer column using the id column - must fit the Counter and PrimaryId interfaces
    • DELETE
      • (deleteBy) using a custom where clause
      • (deleteOneById) - must fit the PrimaryId interface
    • Archive
      • (deactivateOneById) Deactivate a row using the id column - must fit the Activated and PrimaryId interfaces
      • (archiveOneById) Soft DELETE a row using the id column - must fit the Archive interface
      • (archiveCompoundBy) Soft Compound DELETE using a custom where clause - must fit the ArchiveCompound interface
      • (archiveCompoundOneById) Soft Compound DELETE a row using the id column - must fit the ArchiveCompound and PrimaryId interfaces
    • SELECT
      • Transforms
        • JSON column parse
        • Nest dot notation transform
        • Null out nested objects
      • (get) using the Compositional SQL DSL
      • (getByIdList) using the id column - must fit PrimaryId interface
      • (getOneBy) with custom where clause
      • (getOneById) using the id column - must fit PrimaryId interface
      • (getWhere) using a custom where clause
      • (getWhereParams) using the ObjectHash interface
  • Model
    • Compositional SQL DSL
    • Model Creation DSL
    • Query interface
      • INSERT
        • (insertOne)
        • (insertBatch)
        • Pre-Create intercept
        • Post-Create intercept
      • UPDATE
        • (updateOneById) using the id column - must fit PrimaryId interface
        • (incrementOneById) increment an integer column using the id column - must fit the Counter and PrimaryId interfaces
        • Pre-Update intercept
        • Post-Update intercept
      • DELETE
        • (deleteBy) using a custom where clause
        • (deleteOneById) - must fit the PrimaryId interface
      • Archive
        • (deactivateOneById) Deactivate a row using the id column - must fit the Activated and PrimaryId interfaces
        • (archiveOneById) Soft DELETE a row using the id column - must fit the Archive interface
        • (archiveCompoundBy) Soft Compound DELETE using a custom where clause - must fit the ArchiveCompound interface
        • (archiveCompoundOneById) Soft Compound DELETE a row using the id column - must fit the ArchiveCompound and PrimaryId interfaces
      • SELECT
        • Transforms - (Dependent upon Query Interface implementation)
        • (get) using the Compositional SQL DSL
        • (getByIdList) using the id column - must fit PrimaryId interface
        • (getOneBy) with custom where clause
        • (getOneById) using the id column - must fit PrimaryId interface
        • (getWhere) using a custom where clause
        • (getWhereParams) using the ObjectHash interface
  • Search - This needs some re-design to better fit ReasonML language semantics.
  • Utilities
    • TIMESTAMP conversion
    • ObjectHash interface interpolation
    • Caching

Package Sidebar

Install

npm i bs-crud-functors

Weekly Downloads

9

Version

7.1.2

License

MIT

Unpacked Size

283 kB

Total Files

29

Last publish

Collaborators

  • scull7