mevn-orm 2.2.2

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.
package/.babelrc ADDED
@@ -0,0 +1,3 @@
1
+ {
2
+ "plugins": ["@babel/plugin-proposal-class-properties"]
3
+ }
package/.env.example ADDED
@@ -0,0 +1,9 @@
1
+ NODE_ENV=testing
2
+
3
+ DB_HOST=localhost
4
+ DB_USER=root
5
+ DB_PASSWORD=
6
+ DB_DATABASE=mevn_orm
7
+ DB_CLIENT=mysql2
8
+
9
+ TESTING_DB=sqlite3
package/.eslintrc.json ADDED
@@ -0,0 +1,36 @@
1
+ {
2
+ "env": {
3
+ "commonjs": true,
4
+ "es2021": true,
5
+ "node": true
6
+ },
7
+ "extends": "eslint:recommended",
8
+ "plugins": ["@babel"],
9
+ "parser": "@babel/eslint-parser",
10
+ "parserOptions": {
11
+ "ecmaVersion": 12
12
+ },
13
+ "rules": {
14
+ "no-console":"warn",
15
+ "constructor-super":"off",
16
+ "no-this-before-super":"off",
17
+ "arrow-parens":"error",
18
+ "class-methods-use-this":"error",
19
+ "indent": [
20
+ "error",
21
+ "tab"
22
+ ],
23
+ "linebreak-style": [
24
+ "error",
25
+ "unix"
26
+ ],
27
+ "quotes": [
28
+ "error",
29
+ "single"
30
+ ],
31
+ "semi": [
32
+ "error",
33
+ "never"
34
+ ]
35
+ }
36
+ }
package/.gitattributes ADDED
@@ -0,0 +1,8 @@
1
+ .github export-ignore
2
+ _config.yml export-ignore
3
+ .gitignore export-ignore
4
+ CODE_OF_CONDUCT.md export-ignore
5
+ SECURITY.md export-ignore
6
+ test export-ignore
7
+ test.sh export-ignore
8
+ initDb export-ignore
@@ -0,0 +1,38 @@
1
+ ---
2
+ name: Bug report
3
+ about: Create a report to help us improve
4
+ title: ''
5
+ labels: ''
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **Describe the bug**
11
+ A clear and concise description of what the bug is.
12
+
13
+ **To Reproduce**
14
+ Steps to reproduce the behavior:
15
+ 1. Go to '...'
16
+ 2. Click on '....'
17
+ 3. Scroll down to '....'
18
+ 4. See error
19
+
20
+ **Expected behavior**
21
+ A clear and concise description of what you expected to happen.
22
+
23
+ **Screenshots**
24
+ If applicable, add screenshots to help explain your problem.
25
+
26
+ **Desktop (please complete the following information):**
27
+ - OS: [e.g. iOS]
28
+ - Browser [e.g. chrome, safari]
29
+ - Version [e.g. 22]
30
+
31
+ **Smartphone (please complete the following information):**
32
+ - Device: [e.g. iPhone6]
33
+ - OS: [e.g. iOS8.1]
34
+ - Browser [e.g. stock browser, safari]
35
+ - Version [e.g. 22]
36
+
37
+ **Additional context**
38
+ Add any other context about the problem here.
@@ -0,0 +1,20 @@
1
+ ---
2
+ name: Feature request
3
+ about: Suggest an idea for this project
4
+ title: ''
5
+ labels: ''
6
+ assignees: ''
7
+
8
+ ---
9
+
10
+ **Is your feature request related to a problem? Please describe.**
11
+ A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
12
+
13
+ **Describe the solution you'd like**
14
+ A clear and concise description of what you want to happen.
15
+
16
+ **Describe alternatives you've considered**
17
+ A clear and concise description of any alternative solutions or features you've considered.
18
+
19
+ **Additional context**
20
+ Add any other context or screenshots about the feature request here.
@@ -0,0 +1,30 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: npm
4
+ directory: '/'
5
+ schedule:
6
+ interval: daily
7
+ time: '00:00'
8
+ open-pull-requests-limit: 10
9
+ reviewers:
10
+ - stanleymasinde
11
+ assignees:
12
+ - stanleymasinde
13
+ commit-message:
14
+ prefix: fix
15
+ prefix-development: chore
16
+ include: scope
17
+ - package-ecosystem: github-actions
18
+ directory: '/'
19
+ schedule:
20
+ interval: daily
21
+ time: '00:00'
22
+ open-pull-requests-limit: 10
23
+ reviewers:
24
+ - stanleymasinde
25
+ assignees:
26
+ - stanleymasinde
27
+ commit-message:
28
+ prefix: fix
29
+ prefix-development: chore
30
+ include: scope
@@ -0,0 +1,31 @@
1
+ # This workflow will do a clean install of node dependencies, build the source code and run tests across different versions of node
2
+ # For more information see: https://help.github.com/actions/language-and-framework-guides/using-nodejs-with-github-actions
3
+
4
+ name: Node.js CI
5
+
6
+ on:
7
+ push:
8
+ branches: [ main ]
9
+ pull_request:
10
+ branches: [ main ]
11
+
12
+ jobs:
13
+ build:
14
+
15
+ runs-on: ubuntu-latest
16
+
17
+ strategy:
18
+ matrix:
19
+ node-version: [12.x, 14.x, 15.x]
20
+ # See supported Node.js release schedule at https://nodejs.org/en/about/releases/
21
+
22
+ steps:
23
+ - uses: actions/checkout@v2
24
+ - name: Use Node.js ${{ matrix.node-version }}
25
+ uses: actions/setup-node@v2
26
+ with:
27
+ node-version: ${{ matrix.node-version }}
28
+ - run: cp .env.example .env
29
+ - run: npm ci
30
+ - run: npm run build --if-present
31
+ - run: npm test
@@ -0,0 +1,76 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, sex characteristics, gender identity and expression,
9
+ level of experience, education, socio-economic status, nationality, personal
10
+ appearance, race, religion, or sexual identity and orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at stanleyoren@gmail.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html
72
+
73
+ [homepage]: https://www.contributor-covenant.org
74
+
75
+ For answers to common questions about this code of conduct, see
76
+ https://www.contributor-covenant.org/faq
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2021 StanoJs
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,29 @@
1
+ # Mevn-orm
2
+ ![npm](https://img.shields.io/npm/v/mevn-orm?style=for-the-badge)
3
+ [![GitHub license](https://img.shields.io/github/license/stanleymasinde/mevn-orm?style=for-the-badge)](https://github.com/StanleyMasinde/mevn-orm/blob/master/LICENSE)
4
+ ![GitHub issues](https://img.shields.io/github/issues/stanleymasinde/mevn-orm?style=for-the-badge)
5
+
6
+ ```javascript
7
+ const { Model } = require('mevn-orm')
8
+
9
+ class User extends Model {}
10
+
11
+ let columns = {
12
+ name: 'John Doe',
13
+ email: 'john@example.com',
14
+ password: secret // remember to hash the password
15
+ }
16
+ User()
17
+ .create(columns)
18
+ .then(created => {
19
+ // Do something after the creation
20
+ })
21
+ .catch(err => {
22
+ // Handle the error
23
+ })
24
+
25
+ // With aync await
26
+ const userId = await User.create(columns)
27
+ ```
28
+
29
+ _Still under development hence not ready for production_
package/index.js ADDED
@@ -0,0 +1,3 @@
1
+ require('dotenv').config()
2
+ const Model = require('./lib/model')
3
+ module.exports = { Model }
package/initDb ADDED
@@ -0,0 +1,104 @@
1
+ #!/bin/env node
2
+ require('dotenv').config()
3
+ const Knex = require('knex')
4
+ const { development, staging, production } = require('./knexfile')
5
+ let config
6
+
7
+ switch (process.env.NODE_ENV) {
8
+ case 'testing':
9
+ config = development
10
+ break
11
+ case 'development':
12
+ config = development
13
+ break
14
+ case 'staging':
15
+ config = staging
16
+ break
17
+ default:
18
+ config = production
19
+ break
20
+ }
21
+ async function initDatabase() {
22
+ const DB = Knex(config)
23
+ await DB.schema.dropTableIfExists('farmers')
24
+ await DB.schema.dropTableIfExists('farms')
25
+ await DB.schema.dropTableIfExists('profiles')
26
+ await DB.schema.dropTableIfExists('articles')
27
+ await DB.schema.createTable('farmers', (table) => {
28
+ table.bigIncrements('id')
29
+ table.string('name')
30
+ table.string('email').unique()
31
+ table.string('password')
32
+ })
33
+ await DB.schema.createTable('farms', (table) => {
34
+ table.bigIncrements('id')
35
+ table.bigInteger('farmer_id')
36
+ table.string('name')
37
+ })
38
+
39
+ await DB.schema.createTable('profiles', (table) => {
40
+ table.bigIncrements('id')
41
+ table.bigInteger('farmer_id')
42
+ table.string('bio')
43
+ })
44
+
45
+ await DB.schema.createTable('articles', (table) => {
46
+ table.bigIncrements('id')
47
+ table.string('title')
48
+ table.text('body')
49
+ table.bigInteger('postable_id')
50
+ table.string('postable_type')
51
+ })
52
+
53
+ await DB.table('Farmers').insert([
54
+ {
55
+ name: 'Jane Doe',
56
+ email: 'jane@mail.com',
57
+ password: 'pasword'
58
+ },
59
+ {
60
+ name: 'Ashley Doe',
61
+ email: 'ashley@mail.com',
62
+ password: 'pasword'
63
+ },
64
+ {
65
+ name: 'Alice Doe',
66
+ email: 'alice@mail.com',
67
+ password: 'pasword'
68
+ }
69
+ ])
70
+
71
+ await DB.table('farms').insert([
72
+ {
73
+ farmer_id: 1,
74
+ name: 'Awesome Farm'
75
+ },
76
+ {
77
+ farmer_id: 1,
78
+ name: 'Awesome Farm two'
79
+ },
80
+ {
81
+ farmer_id: 1,
82
+ name: 'Awesome Farm three'
83
+ }
84
+ ])
85
+
86
+ await DB.table('profiles').insert([
87
+ {
88
+ farmer_id: 1,
89
+ bio: 'Profile for farmer one'
90
+ }
91
+ ])
92
+
93
+ await DB.table('articles').insert([
94
+ {
95
+ title: 'Awesome Post',
96
+ body: 'fffgjdfjdbdb something #1',
97
+ postable_id: 1,
98
+ postable_type: 'Farmer'
99
+ }
100
+ ])
101
+
102
+ process.exit(0)
103
+ }
104
+ initDatabase()
package/knexfile.js ADDED
@@ -0,0 +1,46 @@
1
+ module.exports = {
2
+
3
+ development: {
4
+ client: 'sqlite3',
5
+ connection: {
6
+ filename: './dev.sqlite'
7
+ },
8
+ useNullAsDefault: true,
9
+ migrations: {
10
+ tableName: 'migrations',
11
+ }
12
+ },
13
+
14
+ staging: {
15
+ client: process.env.DB_CLIENT || 'mysql2',
16
+ connection: {
17
+ database: process.env.DB_DATABASE || 'my_db',
18
+ user: process.env.DB_USER || 'username',
19
+ password: process.env.DB_PASSWORD || 'password'
20
+ },
21
+ pool: {
22
+ min: 2,
23
+ max: 10
24
+ },
25
+ migrations: {
26
+ tableName: 'migrations'
27
+ }
28
+ },
29
+
30
+ production: {
31
+ client: process.env.DB_CLIENT || 'mysql2',
32
+ connection: {
33
+ database: process.env.DB_DATABASE || 'my_db',
34
+ user: process.env.DB_USER || 'username',
35
+ password: process.env.DB_PASSWORD || 'password'
36
+ },
37
+ pool: {
38
+ min: 2,
39
+ max: 10
40
+ },
41
+ migrations: {
42
+ tableName: 'migrations'
43
+ }
44
+ }
45
+
46
+ }
package/lib/model.js ADDED
@@ -0,0 +1,125 @@
1
+ const { development, staging, production } = require('../knexfile')
2
+ const pluralize = require('pluralize')
3
+ let config
4
+ switch (process.env.NODE_ENV) {
5
+ case 'testing':
6
+ config = development
7
+ break
8
+ case 'development':
9
+ config = development
10
+ break
11
+ case 'staging':
12
+ config = staging
13
+ break
14
+ default:
15
+ config = production
16
+ break
17
+ }
18
+ const DB = require('knex')(config)
19
+ class Model {
20
+ #private
21
+ static table = pluralize(this.name.toLowerCase())
22
+ static currentQuery
23
+ constructor(properties) {
24
+ for (const key in properties) {
25
+ this[key] = properties[key]
26
+ }
27
+ this.fillable = []
28
+ this.hidden = []
29
+ this.#private = ['fillable', 'hidden', 'table']
30
+ this.modelName = this.constructor.name.toLowerCase()
31
+ this.table = pluralize(this.modelName)
32
+ }
33
+
34
+ /**
35
+ * Save a model to the database
36
+ */
37
+ async save() {
38
+ try {
39
+ let rows = {}
40
+ this.fillable.forEach((f) => {
41
+ rows[f] = this[f]
42
+ })
43
+ const id = await DB(this.table)
44
+ .insert(rows)
45
+ const fields = await DB(this.table).where({ id }).first()
46
+ for (const f in fields) {
47
+ this[f] = fields[f]
48
+ }
49
+ return this.stripColumns(this)
50
+ } catch (error) {
51
+ console.log(error)
52
+ }
53
+ }
54
+
55
+ /**
56
+ * --------------|
57
+ * Relationships |
58
+ * --------------|
59
+ */
60
+
61
+ /**
62
+ * One to one relationship
63
+ * @param {*} related
64
+ */
65
+ async hasOne(Related, localKey, foreignKey) {
66
+ const table = new Related().table
67
+ const relation = {}
68
+ if (!localKey) {
69
+ localKey = this.id
70
+ }
71
+ if (!foreignKey) {
72
+ foreignKey = `${this.modelName}_id`
73
+ }
74
+ relation[foreignKey] = localKey
75
+ const res = await DB(table).where(relation).first()
76
+ if (res) {
77
+ return this.stripColumns(new Related(res))
78
+ }
79
+ return null
80
+ }
81
+ // hasMany(related) {}
82
+ // hasManyThrough(related) {}
83
+ // belongsTo(related) {}
84
+ // belongsToMany(related) {}
85
+
86
+ /**
87
+ * Where condition
88
+ * @param {*} conditions
89
+ * @returns
90
+ */
91
+ static where(conditions = {}) {
92
+ this.currentQuery = DB(pluralize(this.name.toLowerCase()))
93
+ .where(conditions)
94
+ return this
95
+ }
96
+
97
+ /*ß
98
+ * Return the first model
99
+ * @param {*} columns
100
+ */
101
+ static async first(columns) {
102
+ try {
103
+ if (!this.currentQuery) {
104
+ const rows = await DB(this.table).first(columns)
105
+ return new this(rows)
106
+ }
107
+ } catch (error) {
108
+ console.log(error)
109
+ }
110
+ }
111
+
112
+
113
+ /**
114
+ * Delete columns that are not needed
115
+ *
116
+ */
117
+ stripColumns(Model) {
118
+ this.#private.concat(this.hidden).forEach((h) => {
119
+ delete Model[h]
120
+ })
121
+ return Model
122
+ }
123
+
124
+ }
125
+ module.exports = Model
package/package.json ADDED
@@ -0,0 +1,54 @@
1
+ {
2
+ "name": "mevn-orm",
3
+ "version": "2.2.2",
4
+ "description": "simple ORM for express js",
5
+ "type": "commonjs",
6
+ "scripts": {
7
+ "pretest": "node initDb",
8
+ "test": "mocha --exit",
9
+ "init:db": "node initDb",
10
+ "migrate": "knex migrate:latest",
11
+ "lint": "eslint --ext .js ./"
12
+ },
13
+ "peerDependencies": {
14
+ "knex": "^0.95"
15
+ },
16
+ "keywords": [
17
+ "ORM",
18
+ "express",
19
+ "Mysql",
20
+ "mevn"
21
+ ],
22
+ "author": "Stanley Masinde",
23
+ "license": "MIT",
24
+ "dependencies": {
25
+ "dotenv": "^8.2.0",
26
+ "knex": "^0.95",
27
+ "pluralize": "^8.0.0"
28
+ },
29
+ "devDependencies": {
30
+ "@babel/cli": "^7.13.16",
31
+ "@babel/core": "^7.13.16",
32
+ "@babel/eslint-parser": "^7.13.14",
33
+ "@babel/eslint-plugin": "^7.13.16",
34
+ "@babel/plugin-proposal-class-properties": "^7.13.0",
35
+ "chai": "^4.2.0",
36
+ "eslint": "^7.25.0",
37
+ "faker": "^5.5.3",
38
+ "mocha": "^9.1.2",
39
+ "sqlite3": "^5.0.0"
40
+ },
41
+ "directories": {
42
+ "test": "test"
43
+ },
44
+ "private": false,
45
+ "repository": {
46
+ "type": "git",
47
+ "url": "git+https://github.com/StanleyMasinde/mevn-orm.git"
48
+ },
49
+ "bugs": {
50
+ "url": "https://github.com/StanleyMasinde/mevn-orm/issues"
51
+ },
52
+ "homepage": "https://github.com/StanleyMasinde/mevn-orm#readme",
53
+ "main": "dist/index.js"
54
+ }
@@ -0,0 +1,43 @@
1
+ /* eslint-disable no-undef */
2
+ const { Model } = require('../index')
3
+ const faker = require('faker')
4
+ const { expect } = require('chai')
5
+ class Profile extends Model {
6
+ fillable = ['farmer_id', 'bio']
7
+ }
8
+ class Farmer extends Model {
9
+ fillable = ['name', 'email', 'password']
10
+ hidden = ['password']
11
+
12
+ profile() {
13
+ return this.hasOne(Profile)
14
+ }
15
+ }
16
+
17
+ describe('#Model tests', () => {
18
+ it('#Model instance', async () => {
19
+ const farmer = new Farmer({
20
+ name: faker.name.findName(),
21
+ email: faker.internet.email(),
22
+ password: faker.internet.password()
23
+ })
24
+ await farmer.save()
25
+ expect(farmer).to.an('Object')
26
+ })
27
+
28
+ it('#Has one relationship', async () => {
29
+ const farmer = new Farmer({
30
+ name: faker.name.findName(),
31
+ email: faker.internet.email(),
32
+ password: faker.internet.password()
33
+ })
34
+ await farmer.save()
35
+ await new Profile({
36
+ farmer_id: farmer.id,
37
+ bio: faker.lorem.sentence()
38
+ }).save()
39
+ expect(farmer).to.an('Object')
40
+ const farmerProfile = await farmer.profile()
41
+ expect(farmerProfile).to.haveOwnProperty('farmer_id', farmer.id)
42
+ })
43
+ })