@ihago.santos/fluentsql 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.
package/index.js ADDED
@@ -0,0 +1,3 @@
1
+ import FluentSQLBuilder from "./src/fluentSQL.js";
2
+
3
+ export default FluentSQLBuilder;
@@ -0,0 +1,203 @@
1
+ /*
2
+ * For a detailed explanation regarding each configuration property, visit:
3
+ * https://jestjs.io/docs/en/configuration.html
4
+ */
5
+
6
+ const config = {
7
+ // All imported modules in your tests should be mocked automatically
8
+ // automock: false,
9
+
10
+ // Stop running tests after `n` failures
11
+ // bail: 0,
12
+
13
+ // The directory where Jest should store its cached dependency information
14
+ // cacheDirectory: "/private/var/folders/w0/tmhy86g10cb8k2883jbs63tm0000gn/T/jest_dx",
15
+
16
+ // Automatically clear mock calls and instances between every test
17
+ clearMocks: true,
18
+
19
+ // Indicates whether the coverage information should be collected while executing the test
20
+ // collectCoverage: false,
21
+
22
+ // An array of glob patterns indicating a set of files for which coverage information should be collected
23
+ // collectCoverageFrom: undefined,
24
+
25
+ // The directory where Jest should output its coverage files
26
+ coverageDirectory: "coverage",
27
+
28
+ // An array of regexp pattern strings used to skip coverage collection
29
+ // coveragePathIgnorePatterns: [
30
+ // "/node_modules/"
31
+ // ],
32
+
33
+ // Indicates which provider should be used to instrument code for coverage
34
+ coverageProvider: "v8",
35
+
36
+ // A list of reporter names that Jest uses when writing coverage reports
37
+ coverageReporters: [
38
+ "json",
39
+ "text",
40
+ "lcov",
41
+ "clover"
42
+ ],
43
+
44
+ // An object that configures minimum threshold enforcement for coverage results
45
+ coverageThreshold: {
46
+ global: {
47
+ branches: 100,
48
+ functions: 100,
49
+ lines: 100,
50
+ statements: 100
51
+ }
52
+ },
53
+
54
+ // A path to a custom dependency extractor
55
+ // dependencyExtractor: undefined,
56
+
57
+ // Make calling deprecated APIs throw helpful error messages
58
+ // errorOnDeprecated: false,
59
+
60
+ // Force coverage collection from ignored files using an array of glob patterns
61
+ // forceCoverageMatch: [],
62
+
63
+ // A path to a module which exports an async function that is triggered once before all test suites
64
+ // globalSetup: undefined,
65
+
66
+ // A path to a module which exports an async function that is triggered once after all test suites
67
+ // globalTeardown: undefined,
68
+
69
+ // A set of global variables that need to be available in all test environments
70
+ // globals: {},
71
+
72
+ // The maximum amount of workers used to run your tests. Can be specified as % or a number. E.g. maxWorkers: 10% will use 10% of your CPU amount + 1 as the maximum worker number. maxWorkers: 2 will use a maximum of 2 workers.
73
+ // maxWorkers: "50%",
74
+
75
+ // An array of directory names to be searched recursively up from the requiring module's location
76
+ // moduleDirectories: [
77
+ // "node_modules"
78
+ // ],
79
+
80
+ // An array of file extensions your modules use
81
+ // moduleFileExtensions: [
82
+ // "js",
83
+ // "json",
84
+ // "jsx",
85
+ // "ts",
86
+ // "tsx",
87
+ // "node"
88
+ // ],
89
+
90
+ // A map from regular expressions to module names or to arrays of module names that allow to stub out resources with a single module
91
+ // moduleNameMapper: {},
92
+
93
+ // An array of regexp pattern strings, matched against all module paths before considered 'visible' to the module loader
94
+ // modulePathIgnorePatterns: [],
95
+
96
+ // Activates notifications for test results
97
+ // notify: false,
98
+
99
+ // An enum that specifies notification mode. Requires { notify: true }
100
+ // notifyMode: "failure-change",
101
+
102
+ // A preset that is used as a base for Jest's configuration
103
+ // preset: undefined,
104
+
105
+ // Run tests from one or more projects
106
+ // projects: undefined,
107
+
108
+ // Use this configuration option to add custom reporters to Jest
109
+ // reporters: undefined,
110
+
111
+ // Automatically reset mock state between every test
112
+ // resetMocks: false,
113
+
114
+ // Reset the module registry before running each individual test
115
+ // resetModules: false,
116
+
117
+ // A path to a custom resolver
118
+ // resolver: undefined,
119
+
120
+ // Automatically restore mock state between every test
121
+ // restoreMocks: false,
122
+
123
+ // The root directory that Jest should scan for tests and modules within
124
+ // rootDir: undefined,
125
+
126
+ // A list of paths to directories that Jest should use to search for files in
127
+ // roots: [
128
+ // "<rootDir>"
129
+ // ],
130
+
131
+ // Allows you to use a custom runner instead of Jest's default test runner
132
+ // runner: "jest-runner",
133
+
134
+ // The paths to modules that run some code to configure or set up the testing environment before each test
135
+ // setupFiles: [],
136
+
137
+ // A list of paths to modules that run some code to configure or set up the testing framework before each test
138
+ // setupFilesAfterEnv: [],
139
+
140
+ // The number of seconds after which a test is considered as slow and reported as such in the results.
141
+ // slowTestThreshold: 5,
142
+
143
+ // A list of paths to snapshot serializer modules Jest should use for snapshot testing
144
+ // snapshotSerializers: [],
145
+
146
+ // The test environment that will be used for testing
147
+ testEnvironment: "node",
148
+
149
+ // Options that will be passed to the testEnvironment
150
+ // testEnvironmentOptions: {},
151
+
152
+ // Adds a location field to test results
153
+ // testLocationInResults: false,
154
+
155
+ // The glob patterns Jest uses to detect test files
156
+ // testMatch: [
157
+ // "**/__tests__/**/*.[jt]s?(x)",
158
+ // "**/?(*.)+(spec|test).[tj]s?(x)"
159
+ // ],
160
+
161
+ // An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
162
+ // testPathIgnorePatterns: [
163
+ // "/node_modules/"
164
+ // ],
165
+
166
+ // The regexp pattern or array of patterns that Jest uses to detect test files
167
+ // testRegex: [],
168
+
169
+ // This option allows the use of a custom results processor
170
+ // testResultsProcessor: undefined,
171
+
172
+ // This option allows use of a custom test runner
173
+ // testRunner: "jasmine2",
174
+
175
+ // This option sets the URL for the jsdom environment. It is reflected in properties such as location.href
176
+ // testURL: "http://localhost",
177
+
178
+ // Setting this value to "fake" allows the use of fake timers for functions such as "setTimeout"
179
+ // timers: "real",
180
+
181
+ // A map from regular expressions to paths to transformers
182
+ // transform: undefined,
183
+
184
+ // An array of regexp pattern strings that are matched against all source file paths, matched files will skip transformation
185
+ // transformIgnorePatterns: [
186
+ // "/node_modules/",
187
+ // "\\.pnp\\.[^\\/]+$"
188
+ // ],
189
+
190
+ // An array of regexp pattern strings that are matched against all modules before the module loader will automatically return a mock for them
191
+ // unmockedModulePathPatterns: undefined,
192
+
193
+ // Indicates whether each individual test should be reported during the run
194
+ // verbose: undefined,
195
+
196
+ // An array of regexp patterns that are matched against all source file paths before re-running tests in watch mode
197
+ // watchPathIgnorePatterns: [],
198
+
199
+ // Whether to use watchman for file crawling
200
+ // watchman: true,
201
+ };
202
+
203
+ export default Object.assign({}, config);
package/package.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "@ihago.santos/fluentsql",
3
+ "version": "1.0.0",
4
+ "description": "",
5
+ "main": "index.js",
6
+ "type": "module",
7
+ "scripts": {
8
+ "start": "node src/",
9
+ "test": "NODE_OPTIONS=--experimental-vm-modules npx jest --config jest.config.mjs ",
10
+ "test:cov": "NODE_OPTIONS=--experimental-vm-modules npx jest --config jest.config.mjs --coverage ",
11
+ "test:watch": "NODE_OPTIONS=--experimental-vm-modules npx jest --config jest.config.mjs --watchAll "
12
+ },
13
+ "keywords": [],
14
+ "author": "",
15
+ "license": "ISC",
16
+ "devDependencies": {
17
+ "jest": "^30.2.0"
18
+ }
19
+ }
@@ -0,0 +1,101 @@
1
+ export default class FluentSQLBuilder {
2
+ #database = []
3
+ #limit = 0
4
+ #select = []
5
+ #where = []
6
+ #orderBy = ''
7
+
8
+ constructor({ database }) {
9
+ this.#database = database
10
+ }
11
+
12
+ static for(database) {
13
+ return new FluentSQLBuilder({ database })
14
+ }
15
+ limit(max) {
16
+ this.#limit = max
17
+
18
+ return this
19
+ }
20
+ select(props) {
21
+ this.#select = props
22
+
23
+ return this
24
+ }
25
+
26
+ where(query) {
27
+ // {category: 'developer'}
28
+ // {category: /dev/}
29
+
30
+
31
+ const [[prop, selectedValue]] = Object.entries(query)
32
+ const whereFilter = selectedValue instanceof RegExp ?
33
+ selectedValue :
34
+ new RegExp(selectedValue)
35
+
36
+ /*
37
+ [
38
+ [category, 'developer']
39
+ ]
40
+ */
41
+
42
+ this.#where.push({ prop, filter: whereFilter})
43
+
44
+ return this
45
+ }
46
+
47
+ orderBy(field) {
48
+ this.#orderBy = field
49
+
50
+ return this
51
+ }
52
+ #performLimit(results) {
53
+ return this.#limit && results.length === this.#limit
54
+ }
55
+
56
+ #performWhere(item) {
57
+ for( const { filter, prop} of this.#where) {
58
+ if(!filter.test(item[prop])) return false
59
+ }
60
+
61
+ return true
62
+ }
63
+ #performSelect(item) {
64
+ const currentItem = {}
65
+ const entries = Object.entries(item)
66
+ for(const [ key, value] of entries) {
67
+ if(this.#select.length && !this.#select.includes(key)) continue
68
+
69
+ currentItem[key] = value
70
+ }
71
+
72
+ return currentItem
73
+ }
74
+ #performOrderBy(results) {
75
+
76
+ if(!this.#orderBy) return results
77
+
78
+ return results.sort((prev, next) => {
79
+ return prev[this.#orderBy].localeCompare(next[this.#orderBy])
80
+ })
81
+
82
+ }
83
+
84
+ build() {
85
+ const results = []
86
+ for (const item of this.#database) {
87
+ if (!this.#performWhere(item)) continue;
88
+
89
+ const currentItem = this.#performSelect(item)
90
+ results.push(currentItem)
91
+
92
+ if (this.#performLimit(results)) break;
93
+
94
+ }
95
+
96
+
97
+ const finalResult = this.#performOrderBy(results)
98
+ return finalResult
99
+ }
100
+
101
+ }
@@ -0,0 +1,99 @@
1
+ import { expect, describe, test } from '@jest/globals'
2
+ import FluentSQLBuilder from '../src/fluentSQL'
3
+
4
+ const data = [
5
+ {
6
+ id: 0,
7
+ name: 'erickwendel',
8
+ category: 'developer'
9
+ },
10
+ {
11
+ id: 1,
12
+ name: 'mariazinha',
13
+ category: 'developer'
14
+ },
15
+ {
16
+ id: 2,
17
+ name: 'joaozin',
18
+ category: 'manager'
19
+ },
20
+ ]
21
+
22
+ describe('Test Suite for FluentSQL Builder', () => {
23
+ test('#for should return a FluentSQLBuilder instance', () => {
24
+ const result = FluentSQLBuilder.for(data)
25
+ const expected = new FluentSQLBuilder({ database: data })
26
+ expect(result).toStrictEqual(expected)
27
+ })
28
+ test('#build should return the empty object instance', () => {
29
+ const result = FluentSQLBuilder.for(data).build()
30
+ const expected = data
31
+ expect(result).toStrictEqual(expected)
32
+ })
33
+
34
+ test('#limit given a colletion it should limit results', () => {
35
+ const result = FluentSQLBuilder.for(data).limit(1).build()
36
+ const expected = [data[0]]
37
+
38
+ expect(result).toStrictEqual(expected)
39
+ })
40
+ test('#where given a collection it should filter data', () => {
41
+ const result = FluentSQLBuilder.for(data)
42
+ .where({
43
+ category: /^dev/
44
+ })
45
+ .build()
46
+
47
+ const expected = data.filter(({ category }) => category.slice(0, 3) === 'dev')
48
+
49
+
50
+ expect(result).toStrictEqual(expected)
51
+ })
52
+ test('#select given a collection it should return only specifc fields', () => {
53
+ const result = FluentSQLBuilder.for(data)
54
+ .select(['name', 'category'])
55
+ .build()
56
+
57
+ const expected = data.map(({ name, category }) => ({ name, category }))
58
+
59
+ expect(result).toStrictEqual(expected)
60
+ })
61
+ test('#orderBy given a collection it should order results by field', () => {
62
+ const result = FluentSQLBuilder.for(data)
63
+ .orderBy('name')
64
+ .build()
65
+
66
+ const expected = [
67
+ {
68
+ id: 0,
69
+ name: 'erickwendel',
70
+ category: 'developer'
71
+ },
72
+ {
73
+ id: 2,
74
+ name: 'joaozin',
75
+ category: 'manager'
76
+ },
77
+ {
78
+ id: 1,
79
+ name: 'mariazinha',
80
+ category: 'developer'
81
+ },
82
+ ]
83
+
84
+ expect(result).toStrictEqual(expected)
85
+ })
86
+
87
+ test('pipeline', () => {
88
+ const result = FluentSQLBuilder.for(data)
89
+ .where({ category: "developer" })
90
+ .where({ name: /m/ })
91
+ .select(['name', 'category'])
92
+ .orderBy('name')
93
+
94
+ .build()
95
+
96
+ const expected = data.filter(({ id }) => id === 1).map(({ name, category }) => ({ name, category }))
97
+ expect(result).toStrictEqual(expected)
98
+ })
99
+ })