Skip to content

Commit 665cb34

Browse files
committed
refactor: use gitbreaker instead of node-gitlab
1 parent 96cfed6 commit 665cb34

10 files changed

+4767
-116
lines changed

.babelrc

+3-3
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,8 @@
1010
]
1111
],
1212
"plugins": [
13-
"transform-object-rest-spread",
14-
"transform-class-properties",
15-
"transform-es2015-classes"
13+
"@babel/plugin-proposal-object-rest-spread",
14+
"@babel/plugin-transform-classes",
15+
"@babel/plugin-proposal-class-properties"
1616
]
1717
}

README.md

+26-8
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# gitlab-db
2-
A lightweight GitLab based JSON database with Mongo-style API. Backed by [node-gitlab](https://github.com/node-gitlab/node-gitlab) and [mingo](https://github.com/kofrasa/mingo).
2+
A lightweight Gitlab based JSON database with Mongo-style API. Backed by [gitbreaker](https://github.com/jdalrymple/gitbeaker) and [mingo](https://github.com/kofrasa/mingo).
33

44
[![NPM version][npm-image]][npm-url]
55
[![Downloads][downloads-image]][npm-url]
@@ -17,10 +17,10 @@ npm i gitlab-db
1717
## Quick Start
1818

1919
```js
20-
import GitLabDB from 'gitlab-db'
20+
import GitlabDB from 'gitlab-db'
2121

2222
// Instantiate a database
23-
const db = new GitLabDB('apple', {
23+
const db = new GitlabDB('apple', {
2424
url: 'http://gitlab.example.com',
2525
token: 'your_access_token',
2626
repo: 'group/repo',
@@ -46,13 +46,13 @@ Repository structure will be:
4646

4747
## API
4848

49-
Note: As all APIs returns a promise. I highly recommend the `yield` statement like the following:
49+
Note: As all APIs returns a promise. I highly recommend the `async/await` statement like the following:
5050

5151
```js
52-
const result = yield db.collection('product').save({ name: 'iphone', v: '8', price: 699 })
52+
const result = await db.collection('product').save({ name: 'iphone', v: '8', price: 699 })
5353
```
5454

55-
### constructor(dbName, options)
55+
### constructor(dbName, options[, customGitlabAPI])
5656

5757
Instantiate a database.
5858

@@ -61,6 +61,8 @@ Instantiate a database.
6161
- **url:** `String` Specify gitlab url, eg: `http://gitlab.example.com`.
6262
- **token:** `String` Specify your personal access token.
6363
- **repo:** `String` Specify repository name and group belongs to, format: `group/repo`.
64+
- **branch:** `String` Optional, specify branch, default: `main`.
65+
- **customGitlabAPI:** `String` Specify your custom GitlabAPI like `@gitbeaker/browser`.
6466

6567
### db.createCollection(collectionName [, documents])
6668

@@ -157,12 +159,28 @@ Returns like:
157159
true
158160
```
159161

160-
### Next
162+
## Use in Browser
163+
164+
```js
165+
import { Gitlab } from '@gitbeaker/browser';
166+
import GitlabDB from 'gitlab-db'
167+
168+
// Instantiate a database
169+
const db = new GitlabDB('apple', {
170+
url: 'http://gitlab.example.com',
171+
token: 'your_access_token',
172+
repo: 'group/repo',
173+
}, Gitlab)
174+
175+
// ETC...
176+
```
177+
178+
## Next
161179

162180
- [ ] model check
163181
- [ ] collection deletion
164182

165-
### Test
183+
## Test
166184

167185
Config your environment variables `GITLAB_URL` `ACCESS_TOKEN` `REPO`, and run tests with:
168186

package.json

+25-24
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
{
22
"name": "gitlab-db",
3-
"version": "0.5.0",
3+
"version": "1.0.0",
44
"description": "A lightweight GitLab based JSON database with Mongo-style API",
55
"repository": {
66
"type": "git",
@@ -10,33 +10,34 @@
1010
"scripts": {
1111
"lint": "eslint --ext .js src",
1212
"build": "babel src --out-dir dist",
13-
"test": "npm run build && node ./node_modules/mocha-webpack/bin/mocha-webpack --webpack-config webpack.test.config.js \"test/*.test.js\"",
14-
"publishOnly": "npm run build && npm publish"
13+
"test": "npm run build && node ./node_modules/mochapack/bin/mochapack --webpack-config webpack.test.config.js \"test/*.test.js\"",
14+
"prepublishOnly": "npm run lint && npm run build",
15+
"postpublish": "PACKAGE_VERSION=$(cat package.json | grep \\\"version\\\" | head -1 | awk -F: '{ print $2 }' | sed 's/[\",]//g' | tr -d '[[:space:]]') && git tag $PACKAGE_VERSION && git push --tags"
1516
},
1617
"dependencies": {
17-
"gitlab": "^1.7.1",
18-
"mingo": "^2.1.1",
19-
"uuid": "^3.1.0"
18+
"@gitbeaker/node": "^33.0.0",
19+
"mingo": "^4.1.4",
20+
"uuid": "^8.3.2"
2021
},
2122
"devDependencies": {
22-
"assert": "^1.4.1",
23-
"babel-cli": "^6.26.0",
24-
"babel-loader": "^7.0.0",
25-
"babel-core": "^6.26.0",
26-
"babel-eslint": "^8.0.1",
27-
"babel-plugin-transform-class-properties": "^6.24.1",
28-
"babel-plugin-transform-es2015-classes": "^6.24.1",
29-
"babel-plugin-transform-object-rest-spread": "^6.26.0",
30-
"babel-preset-env": "^1.6.0",
31-
"chai": "^4.0.0",
23+
"@babel/core": "^7.15.0",
24+
"@babel/cli": "^7.14.8",
25+
"@babel/plugin-proposal-object-rest-spread": "^7.14.7",
26+
"@babel/plugin-transform-classes": "^7.14.9",
27+
"@babel/plugin-proposal-class-properties": "^7.14.5",
28+
"assert": "^2.0.0",
29+
"babel-loader": "^8.2.2",
30+
"babel-eslint": "^10.1.0",
31+
"babel-preset-env": "^1.7.0",
32+
"chai": "^4.3.4",
3233
"chai-as-promised": "^7.1.1",
33-
"eslint": "^4.7.2",
34-
"eslint-config-airbnb-base": "^12.0.0",
35-
"eslint-plugin-import": "^2.7.0",
36-
"eslint-plugin-node": "^5.1.1",
37-
"mocha": "^4.1.0",
38-
"mocha-webpack": "^1.0.1",
39-
"webpack": "^2.6.1",
40-
"webpack-node-externals": "^1.6.0"
34+
"eslint": "^7.32.0",
35+
"eslint-config-airbnb-base": "^14.2.1",
36+
"eslint-plugin-import": "^2.24.2",
37+
"eslint-plugin-node": "^11.1.0",
38+
"mocha": "8",
39+
"mochapack": "^2.1.2",
40+
"webpack": "^5.51.1",
41+
"webpack-node-externals": "^3.0.0"
4142
}
4243
}

src/collection.js

+25-25
Original file line numberDiff line numberDiff line change
@@ -10,36 +10,36 @@ export default class Collection {
1010
_getFileContent() {
1111
const { name } = this
1212
const { client, dbName, repo, branch } = this.gitlabConfig
13-
return new Promise((resolve, reject) => {
14-
client.projects.repository.showFile(repo, {
15-
file_path: `${dbName}/${name}.json`,
16-
ref: branch,
17-
}, (data) => {
18-
if (!data) return reject(new Error(`[${name}]: collection does not exist`))
19-
const content = Buffer.from(data.content, 'base64').toString()
20-
try {
21-
const result = JSON.parse(content)
22-
resolve(result)
23-
} catch (e) {
24-
reject(new Error(`[${name}]: collection content must be a valid JSON object`))
25-
}
26-
})
13+
const projectId = repo
14+
const file_path = `${dbName}/${name}.json`
15+
const branch_name = branch
16+
17+
return client.RepositoryFiles.show(projectId, file_path, branch_name).then((data) => {
18+
if (!data) throw new Error(`[${name}]: collection does not exist`)
19+
const content = Buffer.from(data.content, 'base64').toString()
20+
try {
21+
const result = JSON.parse(content)
22+
return result
23+
} catch (e) {
24+
throw new Error(`[${name}]: collection content must be a valid JSON object`)
25+
}
2726
})
2827
}
2928
_writeFileContent(content) {
3029
const { name } = this
3130
const { client, dbName, repo, branch } = this.gitlabConfig
32-
return new Promise((resolve) => {
33-
client.projects.repository.updateFile({
34-
projectId: repo,
35-
file_path: `${dbName}/${name}.json`,
36-
branch_name: branch,
37-
content: JSON.stringify(content),
38-
commit_message: 'Update collection',
39-
}, (data) => {
40-
resolve(data)
41-
})
42-
})
31+
const projectId = repo
32+
const file_path = `${dbName}/${name}.json`
33+
const branch_name = branch
34+
const stringifiedContent = JSON.stringify(content)
35+
const commit_message = 'Update collection'
36+
return client.RepositoryFiles.edit(
37+
projectId,
38+
file_path,
39+
branch_name,
40+
stringifiedContent,
41+
commit_message,
42+
)
4343
}
4444
setOptions(options = {}) {
4545
this.options = { ...this.options, ...options }

src/main.js

+27-30
Original file line numberDiff line numberDiff line change
@@ -1,37 +1,38 @@
1-
import GitLab from 'gitlab'
1+
import { Gitlab } from '@gitbeaker/node'
22
import { initializeCollection, promiseAllSerial } from './utils'
33
import Collection from './collection'
44

55
class GitLabDB {
6-
constructor(dbName, options = {}) {
6+
constructor(dbName, options = {}, customGitlabAPI) {
77
const defaultOptions = {
8-
branch: 'master',
8+
branch: 'main',
99
}
10+
const GitlabClient = customGitlabAPI || Gitlab
1011
this.dbName = dbName
1112
this.options = { ...defaultOptions, ...options }
12-
this.gitlabClient = new GitLab({
13-
url: this.options.url,
13+
this.collections = {}
14+
this.gitlabClient = new GitlabClient({
15+
host: this.options.url,
1416
token: this.options.token,
1517
})
16-
this.collections = {}
1718
}
1819
createCollection(collectionName, documents = []) {
1920
const initialContent = initializeCollection(documents)
2021
const { dbName } = this
2122
const { repo, branch } = this.options
22-
return new Promise((resolve, reject) => {
23-
this.gitlabClient.projects.repository.createFile({
24-
projectId: repo,
25-
file_path: `${dbName}/${collectionName}.json`,
26-
branch_name: branch,
27-
content: JSON.stringify(initialContent),
28-
commit_message: 'Create collection',
29-
}, (data) => {
30-
if (data === true) {
31-
return reject(new Error(`[${collectionName}]: cannot override existing collections, use update instead`))
32-
}
33-
resolve(data)
34-
})
23+
const projectId = repo
24+
const file_path = `${dbName}/${collectionName}.json`
25+
const branch_name = branch
26+
const content = JSON.stringify(initialContent)
27+
const commit_message = 'Create collection'
28+
return this.gitlabClient.RepositoryFiles.create(
29+
projectId,
30+
file_path,
31+
branch_name,
32+
content,
33+
commit_message,
34+
).catch(() => {
35+
throw new Error(`[${collectionName}]: cannot override existing collections, use update instead`)
3536
})
3637
}
3738
createCollections(collectionNames, documentsArray = []) {
@@ -56,17 +57,13 @@ class GitLabDB {
5657
isCollectionExists(collectionName) {
5758
const { dbName } = this
5859
const { repo, branch } = this.options
59-
return new Promise((resolve) => {
60-
this.gitlabClient.projects.repository.showFile(repo, {
61-
file_path: `${dbName}/${collectionName}.json`,
62-
ref: branch,
63-
}, (data) => {
64-
if (data && data.file_name) {
65-
resolve(true)
66-
} else {
67-
resolve(false)
68-
}
69-
})
60+
const projectId = repo
61+
const file_path = `${dbName}/${collectionName}.json`
62+
const branch_name = branch
63+
return this.gitlabClient.RepositoryFiles.show(projectId, file_path, branch_name).then((res) => {
64+
return !!(res && res.file_name)
65+
}).catch((e) => {
66+
return false
7067
})
7168
}
7269
}

src/utils.js

+1-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import uuidv1 from 'uuid/v1'
1+
import { v1 as uuidv1 } from 'uuid'
22

33
export function createNewId() {
44
return uuidv1().replace(/-/g, '')

test/GitLabDB.test.js

+11-19
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ const options = {
1818
repo: process.env.REPO,
1919
}
2020
const testDbName = 'flame'
21-
const testCollectionName = 'project1'
21+
const testCollectionName = 'project'
2222
const testCollectionDocuments = [{ a: 1, b: 3 }, { a: 2, d: 3, b: 3 }, { a: 11, b: 22, c: 33, d: 44 }]
2323
const collectionsWillBeCreatedAndRemoved = ['project4', 'project5']
2424
const newDocument = { a: 41, b: 42 }
@@ -28,24 +28,18 @@ const gitlabDB = new GitLabDB(testDbName, options)
2828
describe('GitLabDB', function() {
2929
this.timeout(200000)
3030

31-
before((done) => {
31+
before(async () => {
3232
console.log(`Creating ${testDbName}/${testCollectionName}.json file in the test repo: ${options.repo}...`)
33-
gitlabDB.isCollectionExists(testCollectionName).then((result) => {
34-
if (!result) {
35-
gitlabDB.createCollection(testCollectionName, testCollectionDocuments).then((data) => {
36-
expect(data).to.have.a.property('file_path')
37-
done()
38-
})
39-
} else {
40-
done()
41-
}
42-
})
33+
const isExists = await gitlabDB.isCollectionExists(testCollectionName)
34+
if (!isExists) {
35+
const data = await gitlabDB.createCollection(testCollectionName, testCollectionDocuments)
36+
expect(data).to.have.a.property('file_path')
37+
}
4338
})
4439

45-
it('collection already exists, should createCollection failed', (done) => {
46-
gitlabDB.createCollection(testCollectionName, [], { key: 'a' }).catch((e) => {
40+
it('collection already exists, should createCollection failed', () => {
41+
return gitlabDB.createCollection(testCollectionName, [], { key: 'a' }).catch((e) => {
4742
expect(e).to.be.an('error')
48-
done()
4943
})
5044
})
5145

@@ -92,10 +86,8 @@ describe('GitLabDB', function() {
9286

9387
after((done) => {
9488
console.log('Get all tests be done, cleaning generated files...')
95-
cleanRepositry(collectionsWillBeCreatedAndRemoved, { ...options, dbName: testDbName }).then((data) => {
96-
const removed_files = data.map(item => {
97-
return JSON.parse(item).file_path
98-
}).join(', ')
89+
cleanRepositry(collectionsWillBeCreatedAndRemoved, { ...options, dbName: testDbName }).then(() => {
90+
const removed_files = collectionsWillBeCreatedAndRemoved.map(item => `${testDbName}/${item}`).join(', ')
9991
console.log(`${removed_files} has been removed`)
10092
done()
10193
})

test/cleanRepositry.js

+3-4
Original file line numberDiff line numberDiff line change
@@ -4,11 +4,10 @@ const child_process = require('child_process')
44
export default function cleanRepositry(collectionNames, options) {
55
const { token, url, repo, dbName } = options
66
const promises = collectionNames.map((collectionName, index) => () => {
7-
return new Promise((resolve, reject) => {
8-
child_process.exec(`curl --request DELETE --header "PRIVATE-TOKEN: ${token}" "${url}/api/v3/projects/${encodeURIComponent(repo)}/repository/files?file_path=${dbName}%2F${collectionName}%2Ejson&branch_name=master&commit_message=Delete%20collection"`, (error, stdout) => {
7+
return new Promise((resolve) => {
8+
child_process.exec(`curl --request DELETE --header 'PRIVATE-TOKEN: ${token}' --header "Content-Type: application/json" --data '{"branch": "main", "author_email": "[email protected]", "author_name": "shiliang", "commit_message": "Delete collection"}' "${url}/api/v4/projects/shiliang%2Fgitlab-db/repository/files/${dbName}%2F${collectionName}%2Ejson"`, (error, stdout) => {
99
if(error) {
10-
console.error('error: ' + error);
11-
return reject(error)
10+
console.log(`[${collectionName}] error: ` + error);
1211
}
1312
resolve(stdout)
1413
});

webpack.test.config.js

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,14 @@
11
var nodeExternals = require('webpack-node-externals')
22

33
module.exports = {
4+
mode: 'production',
45
target: 'node',
56
externals: [nodeExternals()],
67
module: {
7-
loaders: [
8+
rules: [
89
{
910
test: /\.js$/,
10-
loader: 'babel-loader'
11+
use: 'babel-loader'
1112
}
1213
]
1314
}

0 commit comments

Comments
 (0)