@keltoi/hydra 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,33 @@
1
+ # This workflow will run tests using node and then publish a package to GitHub Packages when a release is created
2
+ # For more information see: https://docs.github.com/en/actions/publishing-packages/publishing-nodejs-packages
3
+
4
+ name: Node.js Package
5
+
6
+ on:
7
+ release:
8
+ types: [created]
9
+
10
+ jobs:
11
+ build:
12
+ runs-on: ubuntu-latest
13
+ steps:
14
+ - uses: actions/checkout@v4
15
+ - uses: actions/setup-node@v4
16
+ with:
17
+ node-version: 20
18
+ - run: npm ci
19
+ - run: npm test
20
+
21
+ publish-npm:
22
+ needs: build
23
+ runs-on: ubuntu-latest
24
+ steps:
25
+ - uses: actions/checkout@v4
26
+ - uses: actions/setup-node@v4
27
+ with:
28
+ node-version: 20
29
+ registry-url: https://registry.npmjs.org/
30
+ - run: npm ci
31
+ - run: npm publish
32
+ env:
33
+ NODE_AUTH_TOKEN: ${{secrets.KELTOI_GITPUB}}
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Keltoi
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,2 @@
1
+ # HydraJs
2
+ Boilerplate to start your API from zero using Repository Pattern
package/index.js ADDED
@@ -0,0 +1 @@
1
+ "use strict";var t=require("knex"),e=require("axios");class Model{#t;constructor(t={}){this.#t=t}get key(){return this.#t}set key(t={}){this.#t=t}get entity(){return{}}}class Logged extends Model{#e=new Date;#n=void 0|new Date;#s=!0;constructor({key:t={},createdAt:e=new Date,updatedAt:n=void 0|new Date,active:s=!0}){super(t),this.#s=s,this.#n=n,this.#e=e}get createdAt(){return this.#e}set createdAt(t=new Date){this.createdAt=t}get updatedAt(){return this.#n}set updatedAt(t=new Date){this.#n=t}get active(){return this.#s}set active(t=!0){this.#s=t}static makeMe(e=t(),n=Model,s=(e=new t.TableBuilder)=>{}){return e.schema.createTable(n.name,(t=>{s(t),t.dateTime("createdAt").notNullable().defaultTo(e.fn.now()),t.dateTime("updatedAt").nullable(),t.boolean("active").defaultTo(!0)}))}}class Thing extends Model{#o;constructor({key:t={},name:e=""}){super(t),this.#o=e}get name(){return this.#o}set name(t=""){this.#o=t}get entity(){return{name:this.#o}}static makeMe(e=t(),n=Thing,s=(e=new t.TableBuilder)=>{}){return e.schema.createTable(n.name,(t=>{s(t),t.string(255).notNullable()}))}}let n=class Context{#r;constructor(e=t()){this.#r=e}get db(){return this.#r}unitOfWork(...t){return this.#r.transaction().then((e=>(t.forEach((t=>t.context=e)),{done:()=>e.commit().then((()=>t.forEach((t=>t.resetContext())))),rollback:()=>e.rollback().then((()=>t.forEach((t=>t.resetContext()))))})))}static instance(e=t()){return new Context(e)}async terraform(t=[]){const e=t.map((async t=>{await this.#r.schema.hasTable(t.name)||await t.makeMe(this.#r)}));await Promise.all(e)}},s=class Repository{#o="";myContext;static anyOrError(t,e={code:0,message:""}){if(t)return t;throw e}static setOrEmpty(t=[],e=t=>t){return t.length?t.map(e):[]}constructor(t=Model,e=new n){this.#o=t.name,this.myContext=()=>e.db(this.#o),this.resetContext=()=>{this.myContext=()=>e.db(this.#o)},this.modelInstance=(e={})=>new t(e)}set context(e=t()){this.myContext=()=>e(this.#o)}insert=(t=new Model)=>this.myContext().insert(t.entity,Object.keys(t.key)).then((e=>t.key=e[0])).then((()=>t));update=(t=new Model)=>this.myContext().where(t.key).update(t.entity).then((t=>t>0));delete=(t={})=>this.myContext().where(t).del().then((t=>t>0));get=(t={})=>this.myContext().where(t).first().then(Repository.anyOrError).then(this.modelInstance);list=()=>this.myContext().select().then((t=>Repository.setOrEmpty(t,this.modelInstance)))};class Context{#a;constructor(t=e.create({})){this.#a=t}get http(){return this.#a}}class Repository{#i;constructor(t=Model,e=new Context){this.#i=e,this.modelInstance=(e={})=>new t(e)}static queryString(t={}){return"?"+Object.entries(t).map((([t,e])=>`${t}=${e}`)).join("&")}get context(){return this.#i}}exports.ApiContext=Context,exports.ApiRepository=Repository,exports.ApiRestRepository=class RestRepository extends Repository{constructor(t=Model,e=new Context){super(t,e)}#h=(t="",e=void 0|{})=>this.context.http.get(e?`${t}${Repository.queryString(e)}`:t);get=(t="",e=void 0|{})=>this.#h(t,e).then((t=>this.modelInstance(t)));list=(t="",e=void 0|{})=>this.#h(t,e).then(((t=[])=>t.map((t=>this.modelInstance(t)))));create=(t="",e=new Model)=>this.context.http.post(t,e.entity);update=(t="",e=new Model)=>this.context.http.put(t,e.entity);change=(t="",e=new Model)=>this.context.http.patch(t,e.entity);delete=(t,e=new Model)=>this.context.http.delete(`/${t}`)},exports.DbContext=n,exports.DbLoggedRepository=class LoggedRepository extends s{constructor(t=Logged,e=new n){super(t,e)}deceased=()=>this.myContext().where({active:!1}).select().then((t=>t.map(this.modelInstance)));get=(t={})=>this.myContext().where({...t,active:!0}).first().then(this.modelInstance);before=(t=new Date)=>this.myContext().where("createdAt","<",t.toISOString()).select().then((t=>t.map(this.modelInstance)));after=(t=new Date)=>this.myContext().where("createdAt",">",t.toISOString()).select().then((t=>t.map(this.modelInstance)));list=()=>this.myContext().select().orderBy("createdAt","updatedAt").where({active:!0}).then((t=>t.map(this.modelInstance)));update=(t=new Logged)=>this.myContext().where(t.key).update({...t.entity,updatedAt:new Date}).then((t=>t>0));delete=(t={})=>this.myContext().where(t).update({updatedAt:(new Date).toISOString(),active:!1}).then((t=>t>0))},exports.DbRepository=s,exports.DbThingRepository=class ThingRepository extends s{constructor(t=new n){super(model=Thing,t)}getByName=(t="")=>this.myContext().where({name:t}).select().then((t=>this.modelInstance(t)))},exports.Logged=Logged,exports.Model=Model,exports.Thing=Thing;
package/package.json ADDED
@@ -0,0 +1,30 @@
1
+ {
2
+ "name": "@keltoi/hydra",
3
+ "version": "1.0.0",
4
+ "description": "Boilerplate to start your API from zero using Repository Pattern",
5
+ "main": "index.js",
6
+ "scripts": {
7
+ "test": "npm run build & npm link",
8
+ "build": "rollup -c"
9
+ },
10
+ "repository": {
11
+ "type": "git",
12
+ "url": "git+https://github.com/Keltoi-Tech/HydraJs.git"
13
+ },
14
+ "keywords": [
15
+ "API",
16
+ "RepositoryPattern"
17
+ ],
18
+ "author": "DaniloHenrique",
19
+ "license": "MIT",
20
+ "bugs": {
21
+ "url": "https://github.com/Keltoi-Tech/HydraJs/issues"
22
+ },
23
+ "homepage": "https://github.com/Keltoi-Tech/HydraJs#readme",
24
+ "dependencies": {
25
+ "@rollup/plugin-terser": "^0.4.4",
26
+ "axios": "^1.7.7",
27
+ "knex": "^3.1.0",
28
+ "rollup": "^4.24.4"
29
+ }
30
+ }
@@ -0,0 +1,17 @@
1
+ import terser from '@rollup/plugin-terser';
2
+
3
+ export default {
4
+ input:'src/index.js',
5
+ plugins:[
6
+ terser({
7
+ keep_classnames:true,
8
+ keep_fnames:true
9
+ })
10
+ ],
11
+ output:[
12
+ {
13
+ file:'index.js',
14
+ format:'cjs'
15
+ }
16
+ ]
17
+ }
package/src/index.js ADDED
@@ -0,0 +1,23 @@
1
+ import Logged from './model/logged.js'
2
+ import Model from './model/index.js'
3
+ import Thing from './model/thing.js'
4
+ import DbContext from './repository/db/context.js'
5
+ import DbRepository from './repository/db/index.js'
6
+ import DbLoggedRepository from './repository/db/loggedRepository.js'
7
+ import DbThingRepository from './repository/db/thingRepository.js'
8
+ import ApiContext from './repository/api/context.js'
9
+ import ApiRepository from './repository/api/index.js'
10
+ import ApiRestRepository from './repository/api/restRepository.js'
11
+
12
+ export {
13
+ Model,
14
+ Thing,
15
+ Logged,
16
+ DbContext,
17
+ DbRepository,
18
+ DbLoggedRepository,
19
+ DbThingRepository,
20
+ ApiContext,
21
+ ApiRepository,
22
+ ApiRestRepository
23
+ }
@@ -0,0 +1,12 @@
1
+ export default class Model{
2
+ #key
3
+ constructor(key={}){
4
+ this.#key = key
5
+ }
6
+
7
+ get key(){return this.#key }
8
+ set key(value={}){this.#key=value}
9
+
10
+ get entity(){return {}}
11
+
12
+ }
@@ -0,0 +1,34 @@
1
+ import knex from "knex"
2
+ import Model from "./index.js"
3
+
4
+ export default class Logged extends Model{
5
+ #createdAt=new Date()
6
+ #updatedAt=new Date()|undefined
7
+ #active=true
8
+
9
+ constructor({key={},createdAt=new Date(),updatedAt=new Date()|undefined,active=true}){
10
+ super(key)
11
+ this.#active=active
12
+ this.#updatedAt = updatedAt
13
+ this.#createdAt = createdAt
14
+ }
15
+
16
+ get createdAt(){return this.#createdAt}
17
+ set createdAt(value = new Date()){this.createdAt = value}
18
+
19
+ get updatedAt(){return this.#updatedAt}
20
+ set updatedAt(value = new Date()){this.#updatedAt = value}
21
+
22
+ get active(){return this.#active}
23
+ set active(value = true){this.#active = value}
24
+
25
+ static makeMe(db=knex(),model=Model,schema=(t=new knex.TableBuilder())=>{}){
26
+ return db.schema.createTable(model.name,table=>{
27
+ schema(table)
28
+
29
+ table.dateTime('createdAt').notNullable().defaultTo(db.fn.now())
30
+ table.dateTime('updatedAt').nullable()
31
+ table.boolean('active').defaultTo(true)
32
+ })
33
+ }
34
+ }
@@ -0,0 +1,26 @@
1
+ import knex from "knex";
2
+ import Model from "./index.js";
3
+
4
+
5
+ export default class Thing extends Model{
6
+ #name
7
+ constructor({key={},name=''}){
8
+ super(key)
9
+ this.#name = name
10
+ }
11
+
12
+ get name(){return this.#name}
13
+ set name(value=''){this.#name=value}
14
+
15
+ get entity(){
16
+ return {name:this.#name}
17
+ }
18
+
19
+ static makeMe(db=knex(),thing=Thing,schema=(t=new knex.TableBuilder())=>{}){
20
+ return db.schema.createTable(thing.name,table=>{
21
+ schema(table)
22
+
23
+ table.string(255).notNullable()
24
+ })
25
+ }
26
+ }
@@ -0,0 +1,10 @@
1
+ import axios from "axios"
2
+
3
+ export default class Context{
4
+ #http
5
+ constructor(config=axios.create({})){
6
+ this.#http = config
7
+ }
8
+
9
+ get http(){return this.#http}
10
+ }
@@ -0,0 +1,16 @@
1
+ import Model from "../../model/index.js"
2
+ import Context from "./context.js"
3
+
4
+ export default class Repository{
5
+ #context
6
+ constructor(model=Model,context=new Context()){
7
+ this.#context = context
8
+ this.modelInstance=(m={})=>new model(m)
9
+ }
10
+
11
+ static queryString(param={}){
12
+ return '?' + Object.entries(param).map(([k,v])=>`${k}=${v}`).join('&')
13
+ }
14
+
15
+ get context(){return this.#context}
16
+ }
@@ -0,0 +1,26 @@
1
+ import Model from "../../model/index.js"
2
+ import Context from "./context.js"
3
+ import Repository from "./index.js"
4
+
5
+
6
+ export default class RestRepository extends Repository{
7
+ constructor(model=Model,context=new Context()){
8
+ super(model,context)
9
+ }
10
+
11
+ #httpGet=(route='',query={}|undefined)=>this.context
12
+ .http
13
+ .get(!! query ? `${route}${Repository.queryString(query)}` : route)
14
+
15
+ get=(route='',query={}|undefined)=>this.#httpGet(route,query).then(value=>this.modelInstance(value))
16
+
17
+ list=(route='',query={}|undefined)=>this.#httpGet(route,query).then((values=[])=>values.map(value=>this.modelInstance(value)))
18
+
19
+ create=(route='',model=new Model())=>this.context.http.post(route,model.entity)
20
+
21
+ update=(route='',model=new Model())=>this.context.http.put(route,model.entity)
22
+
23
+ change=(route='',model=new Model())=>this.context.http.patch(route,model.entity)
24
+
25
+ delete=(id,model=new Model())=>this.context.http.delete(`/${id}`)
26
+ }
@@ -0,0 +1,33 @@
1
+ import knex from "knex"
2
+
3
+ export default class Context{
4
+ #db
5
+
6
+ constructor(database=knex()){
7
+ this.#db= database
8
+ }
9
+
10
+ get db(){return this.#db}
11
+
12
+ unitOfWork(...repositories){
13
+ return this.#db.transaction().then(trx=>{
14
+ repositories.forEach(repo=>repo.context = trx)
15
+
16
+ return {
17
+ done:()=>trx.commit().then(()=>repositories.forEach(repo=>repo.resetContext())),
18
+ rollback:()=>trx.rollback().then(()=>repositories.forEach(repo=>repo.resetContext()))
19
+ }
20
+ })
21
+ }
22
+
23
+ static instance(database=knex()){return new Context(database)}
24
+
25
+ async terraform(models=[]){
26
+ const promises = models.map(async model=>{
27
+ const exists = await this.#db.schema.hasTable(model.name)
28
+ if (!exists) await model.makeMe(this.#db)
29
+ })
30
+
31
+ await Promise.all(promises)
32
+ }
33
+ }
@@ -0,0 +1,63 @@
1
+ import knex from "knex";
2
+ import Model from "../../model/index.js";
3
+ import Context from "./context.js";
4
+
5
+
6
+ export default class Repository{
7
+ #name='';
8
+
9
+ myContext
10
+
11
+ static anyOrError(model,err={code:0,message:''}){
12
+ if (!!model) return model
13
+
14
+ throw err;
15
+ }
16
+
17
+ static setOrEmpty(array=[],modeling=(e)=>e){
18
+ return array.length ? array.map(modeling) : []
19
+ }
20
+
21
+
22
+ constructor(model=Model,context=new Context())
23
+ {
24
+ this.#name = model.name
25
+ this.myContext=()=>context.db(this.#name)
26
+ this.resetContext=()=>{
27
+ this.myContext=()=>context.db(this.#name)
28
+ }
29
+ this.modelInstance=(m={})=>new model(m)
30
+ }
31
+
32
+ set context(value=knex()){ this.myContext=()=>value(this.#name)}
33
+
34
+ insert=(model=new Model())=>
35
+ this.myContext()
36
+ .insert(model.entity,Object.keys(model.key))
37
+ .then(ids=>model.key = ids[0])
38
+ .then(()=>model)
39
+
40
+ update=(model=new Model())=>
41
+ this.myContext()
42
+ .where(model.key)
43
+ .update(model.entity)
44
+ .then(affected=>affected > 0)
45
+
46
+ delete=(key={})=>
47
+ this.myContext()
48
+ .where(key)
49
+ .del()
50
+ .then(affected=>affected > 0)
51
+
52
+ get=(key={})=>
53
+ this.myContext()
54
+ .where(key)
55
+ .first()
56
+ .then(Repository.anyOrError)
57
+ .then(this.modelInstance)
58
+
59
+ list=()=>
60
+ this.myContext()
61
+ .select()
62
+ .then(result=>Repository.setOrEmpty(result,this.modelInstance))
63
+ }
@@ -0,0 +1,54 @@
1
+ import Logged from '../../model/logged.js';
2
+ import Context from './context.js';
3
+ import Repository from './index.js';
4
+
5
+ export default class LoggedRepository extends Repository{
6
+ constructor(model=Logged,context=new Context()){
7
+ super(model,context)
8
+ }
9
+
10
+ deceased=()=>this.myContext()
11
+ .where({active:false})
12
+ .select()
13
+ .then(deads=>deads.map(this.modelInstance))
14
+
15
+ get=(key={})=>this.myContext()
16
+ .where({...key,active:true})
17
+ .first()
18
+ .then(this.modelInstance)
19
+
20
+ before=(date=new Date())=>this.myContext()
21
+ .where('createdAt','<',date.toISOString())
22
+ .select()
23
+ .then(result=>result.map(this.modelInstance))
24
+
25
+ after=(date=new Date())=>this.myContext()
26
+ .where('createdAt','>',date.toISOString())
27
+ .select()
28
+ .then(result=>result.map(this.modelInstance))
29
+
30
+ list=()=>this.myContext()
31
+ .select()
32
+ .orderBy('createdAt','updatedAt')
33
+ .where({active:true})
34
+ .then(result=>result.map(this.modelInstance))
35
+
36
+ update=(model=new Logged())=>
37
+ this.myContext()
38
+ .where(model.key)
39
+ .update({
40
+ ...model.entity,
41
+ updatedAt:new Date()
42
+ })
43
+ .then(affected=> affected > 0)
44
+
45
+ delete=(key={})=>
46
+ this.myContext()
47
+ .where(key)
48
+ .update({
49
+ updatedAt:new Date().toISOString(),
50
+ active:false
51
+ })
52
+ .then(affected=> affected > 0)
53
+
54
+ }
@@ -0,0 +1,14 @@
1
+ import Thing from "../../model/thing.js";
2
+ import Context from "./context.js";
3
+ import Repository from "./index.js";
4
+
5
+ export default class ThingRepository extends Repository{
6
+ constructor(context=new Context()){
7
+ super(model=Thing,context)
8
+ }
9
+
10
+ getByName=(name='')=>this.myContext()
11
+ .where({name})
12
+ .select()
13
+ .then(model=>this.modelInstance(model))
14
+ }