diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 95e247d..79da677 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -85,4 +85,3 @@ build_image: only: - tags cache: {} - \ No newline at end of file diff --git a/bin/migration.js b/bin/migration.js index 3818163..957ab22 100644 --- a/bin/migration.js +++ b/bin/migration.js @@ -9,10 +9,14 @@ const listCollection = JSON.parse(process.argv[2]); Will dump and restore each collection from connect to connect-sandbox */ listCollection.forEach(async (collection) => { - if (collection !== '_Session' && collection !== '_User') { - const resultDump = await exec(`mongodump -d connect -c ${collection} --username ${MONGO_USERNAME} --password ${MONGO_PASSWORD}`); - console.log(`${collection}/resultDump:`, resultDump); - const resutlRestore = await exec(`mongorestore -d connect-sandbox -c ${collection} dump/connect/${collection}.bson --username ${MONGO_USERNAME} --password ${MONGO_PASSWORD}`); - console.log(`${collection}/resutlRestore:`, resutlRestore); - } + if (collection !== '_Session' && collection !== '_User') { + const resultDump = await exec( + `mongodump -d connect -c ${collection} --username ${MONGO_USERNAME} --password ${MONGO_PASSWORD}`, + ); + console.log(`${collection}/resultDump:`, resultDump); + const resutlRestore = await exec( + `mongorestore -d connect-sandbox -c ${collection} dump/connect/${collection}.bson --username ${MONGO_USERNAME} --password ${MONGO_PASSWORD}`, + ); + console.log(`${collection}/resutlRestore:`, resutlRestore); + } }); diff --git a/bin/migration_mongo.js b/bin/migration_mongo.js index d4e1681..780c140 100644 --- a/bin/migration_mongo.js +++ b/bin/migration_mongo.js @@ -11,12 +11,12 @@ conn = new Mongo(MONGO_HOST); dbSandbox = conn.getDB('connect-sandbox'); dbSandbox.auth(MONGO_USERNAME, MONGO_PASSWORD); -dbSandbox.getCollectionNames().forEach(collection => { - if (collection !== '_Session' && collection !== '_User') { - dbSandbox.getCollection(collection).drop(); - } +dbSandbox.getCollectionNames().forEach((collection) => { + if (collection !== '_Session' && collection !== '_User') { + dbSandbox.getCollection(collection).drop(); + } }); - -print("\nDelete previous collections") + +print('\nDelete previous collections'); dbSandbox.logout(); diff --git a/bin/performance.js b/bin/performance.js index 49bfbdb..69029a3 100755 --- a/bin/performance.js +++ b/bin/performance.js @@ -10,48 +10,46 @@ const fs = require('fs'); const json2csv = require('json2csv'); // To be changed with the Application to Monitor -const APP_NAME = "7n3k8m-Test"; -const APP_TOKEN = "f81eda23-3bab-466e-89bb-627a96ba3991"; +const APP_NAME = '7n3k8m-Test'; +const APP_TOKEN = 'f81eda23-3bab-466e-89bb-627a96ba3991'; function getHeaderWithToken(sessionToken) { return { 'x-parse-application-id': 'connect', 'x-parse-session-token': sessionToken, - 'content-type': 'application/json' + 'content-type': 'application/json', }; } function writeToCSV(task, quantity, time) { - const newLine = "\r\n"; + const newLine = '\r\n'; const fields = ['date', 'task', 'quantity', 'time']; const data = { - date: new Date(), - task, - quantity, - time - }; + date: new Date(), + task, + quantity, + time, + }; fs.stat('perf.csv', (err) => { if (err === null) { - // write the actual data and end with newline - const csv = json2csv.parse(data, {header: false}) + newLine; - - fs.appendFile('perf.csv', csv, (errW) => { - if (errW) throw errW; - }); - } - else { - // write the headers and newline - console.log('New file, just writing headers'); - const csv = json2csv.parse({}, {fields}) + newLine; + // write the actual data and end with newline + const csv = json2csv.parse(data, { header: false }) + newLine; - fs.appendFile('perf.csv', csv, (errW) => { - if (errW) throw errW; - writeToCSV(task, quantity, time); + fs.appendFile('perf.csv', csv, (errW) => { + if (errW) throw errW; + }); + } else { + // write the headers and newline + console.log('New file, just writing headers'); + const csv = json2csv.parse({}, { fields }) + newLine; + + fs.appendFile('perf.csv', csv, (errW) => { + if (errW) throw errW; + writeToCSV(task, quantity, time); }); } -}); - + }); } async function createObjects(numberOfObject, sessionToken) { @@ -59,19 +57,23 @@ async function createObjects(numberOfObject, sessionToken) { // eslint-disable-next-line no-unused-vars for (const _ of Array(numberOfObject).keys()) { // eslint-disable-next-line no-await-in-loop - await axios.post('http://127.0.0.1:1337/parse/classes/GameScore', + await axios.post( + 'http://127.0.0.1:1337/parse/classes/GameScore', { - score:1337, - playerName:"sample", - cheatMode:false - } - ,{ - headers: getHeaderWithToken(sessionToken) - }); + score: 1337, + playerName: 'sample', + cheatMode: false, + }, + { + headers: getHeaderWithToken(sessionToken), + }, + ); } const t1 = performance.now(); - console.log(`Creation of ${numberOfObject} objects took ${ t1 - t0 } milliseconds.`); - writeToCSV('POST /classes', numberOfObject, t1 - t0) + console.log( + `Creation of ${numberOfObject} objects took ${t1 - t0} milliseconds.`, + ); + writeToCSV('POST /classes', numberOfObject, t1 - t0); } async function readObjects(numberOfObject, sessionToken) { @@ -79,15 +81,15 @@ async function readObjects(numberOfObject, sessionToken) { // eslint-disable-next-line no-unused-vars for (const _ of Array(numberOfObject).keys()) { // eslint-disable-next-line no-await-in-loop - await axios.get('http://127.0.0.1:1337/parse/classes/GameScore', - { - headers: getHeaderWithToken(sessionToken) + await axios.get('http://127.0.0.1:1337/parse/classes/GameScore', { + headers: getHeaderWithToken(sessionToken), }); } const t1 = performance.now(); - console.log(`Reading of ${numberOfObject} bacthes took ${ t1 - t0 } milliseconds.`); - writeToCSV('GET /classes', numberOfObject, t1 - t0) - + console.log( + `Reading of ${numberOfObject} bacthes took ${t1 - t0} milliseconds.`, + ); + writeToCSV('GET /classes', numberOfObject, t1 - t0); } async function readObjectsWithCondition(numberOfObject, sessionToken) { @@ -95,45 +97,41 @@ async function readObjectsWithCondition(numberOfObject, sessionToken) { // eslint-disable-next-line no-unused-vars for (const i of Array(numberOfObject).keys()) { // eslint-disable-next-line no-await-in-loop - await axios.get('http://127.0.0.1:1337/parse/classes/GameScore', - { - params: { - where: {"playerName":"sample","cheatMode":false}, - skip: i * 100 - }, - headers: getHeaderWithToken(sessionToken) - } - ); + await axios.get('http://127.0.0.1:1337/parse/classes/GameScore', { + params: { + where: { playerName: 'sample', cheatMode: false }, + skip: i * 100, + }, + headers: getHeaderWithToken(sessionToken), + }); } const t1 = performance.now(); - console.log(`Reading of ${numberOfObject} bacthes with condition took ${ t1 - t0 } milliseconds.`); - writeToCSV('GET /classes w/ condition', numberOfObject, t1 - t0) - + console.log( + `Reading of ${numberOfObject} bacthes with condition took ${ + t1 - t0 + } milliseconds.`, + ); + writeToCSV('GET /classes w/ condition', numberOfObject, t1 - t0); } - - async function checkAdd() { try { const response = await axios.get('http://127.0.0.1:1337/parse/login', { params: { password: APP_TOKEN, - username: APP_NAME + username: APP_NAME, }, headers: { 'x-parse-application-id': 'connect', - 'x-parse-revocable-session': '1' - } - - }); + 'x-parse-revocable-session': '1', + }, + }); const { sessionToken } = response.data; await createObjects(100, sessionToken); await readObjects(100, sessionToken); await readObjectsWithCondition(100, sessionToken); - - } catch (error) { return console.error(error); } @@ -141,6 +139,4 @@ async function checkAdd() { return 0; } - checkAdd(); - diff --git a/docs/Insomnia-collection.json b/docs/Insomnia-collection.json index cf33531..f42d1c2 100644 --- a/docs/Insomnia-collection.json +++ b/docs/Insomnia-collection.json @@ -435,11 +435,7 @@ "SESSION_TOKEN": "{% response 'body', 'req_b762de04bc504fff8624f92cdb8b32f0', 'b64::JC5zZXNzaW9uVG9rZW4=::46b', 'always' %}" }, "dataPropertyOrder": { - "&": [ - "CONNECT_URI", - "SESSION_TOKEN", - "JWT_TOKEN" - ] + "&": ["CONNECT_URI", "SESSION_TOKEN", "JWT_TOKEN"] }, "isPrivate": false, "metaSortKey": 1563204550618, @@ -466,10 +462,7 @@ "JWT_TOKEN": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJsb2dpbiI6ImJydW5vTWF1cmljZSIsIm5hbWUiOiJCcnVub01hdXJpY2UiLCJpZCI6MjgzODk5OCwiaWF0IjoxNTYyMjI3NzM1OTQwLCJleHAiOjE1NjIzMTQxMzU5NDF9.g-uxZcEFPwqqmG16tA5-Q2fhDlUIYRGXsjnaOzvz7m4" }, "dataPropertyOrder": { - "&": [ - "CONNECT_URI", - "JWT_TOKEN" - ] + "&": ["CONNECT_URI", "JWT_TOKEN"] }, "isPrivate": false, "metaSortKey": 1563204620660, @@ -479,4 +472,4 @@ "_type": "environment" } ] -} \ No newline at end of file +} diff --git a/docs/usage.md b/docs/usage.md index 158d82c..48a203d 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -1,6 +1,6 @@ # Usage Documentations - This documentations is write in purpose to explain how to use the connect application and how to contribute. +This documentations is write in purpose to explain how to use the connect application and how to contribute. ## Sommaire @@ -21,9 +21,9 @@ ## Lexique - User : It's the developer who want to consume the connect api +User : It's the developer who want to consume the connect api - CRI : It's the organisation who manage the "connect" api and manage how it run and evolve. +CRI : It's the organisation who manage the "connect" api and manage how it run and evolve. ## Api usage @@ -44,7 +44,7 @@ curl --request GET \ --url 'https://connect-project.io/parse/login?password=APP_TOKEN&username=APP_ID&=' \ --header 'x-parse-application-id: connect' \ --header 'x-parse-revocable-session: 1' - + Reponse : { "objectId": "xxxxx", "username": "j93mt7-xxxx", @@ -68,7 +68,7 @@ curl --request GET \ --url https://connect-project.io/parse/classes/GameScore/DFwP7JXoa0 \ --header 'x-parse-application-id: connect' \ --header 'x-parse-session-token: r:b003aae18ee536c94aeb07562a4af8e2' - + Response : { "score": 1338, @@ -87,7 +87,7 @@ curl --request GET \ --url https://connect-project.io/parse/classes/GameScore \ --header 'x-parse-application-id: connect' \ --header 'x-parse-session-token: r:b003aae18ee536c94aeb07562a4af8e2' - + Response : { "results": [ @@ -125,31 +125,31 @@ curl --request GET \ The values of the `where` parameter also support comparisons besides exact matching. Instead of an exact value, provide a hash with keys corresponding to the comparisons to do. The `where` parameter supports these options: -| Key | Operation | -|-------------|----------------------------------| -| $lt | Less Than | -| $lte | Less Than Or Equal To | -| $gt | Greater Than | -| $gte | Greater Than Or Equal To | -| $ne | Not Equal To | -| $in | Contained In | -| $nin | Not Contained in | -| $exists | A value is set for the key | -| $select | This matches a value for a key in the result of a different query | -| $dontSelect | Requires that a key's value not match a value for a key in the result of a different query | -| $all | Contains all of the given values | -| $regex | Requires that a key's value match a regular expression | -| $text | Performs a full text search on indexed fields | +| Key | Operation | +| ------------ | ------------------------------------------------------------------------------------------ | +| \$lt | Less Than | +| \$lte | Less Than Or Equal To | +| \$gt | Greater Than | +| \$gte | Greater Than Or Equal To | +| \$ne | Not Equal To | +| \$in | Contained In | +| \$nin | Not Contained in | +| \$exists | A value is set for the key | +| \$select | This matches a value for a key in the result of a different query | +| \$dontSelect | Requires that a key's value not match a value for a key in the result of a different query | +| \$all | Contains all of the given values | +| \$regex | Requires that a key's value match a regular expression | +| \$text | Performs a full text search on indexed fields | In addition to `where`, there are several parameters you can use to configure what types of results are returned by the query. -| Parameter | Use | -|-----------------------------------------------------------------|-----------------------------------------------------------------| -| order | Specify a field to sort by | -| limit | Limit the number of objects returned by the query (it can't be above 100 items) | -| skip | Use with limit to paginate through results | -| keys | Restrict the fields returned by the query | -| include | Use on Pointer columns to return the full object | +| Parameter | Use | +| --------- | ------------------------------------------------------------------------------- | +| order | Specify a field to sort by | +| limit | Limit the number of objects returned by the query (it can't be above 100 items) | +| skip | Use with limit to paginate through results | +| keys | Restrict the fields returned by the query | +| include | Use on Pointer columns to return the full object | You can use the `order` parameter to specify a field to sort by. Prefixing with a negative sign reverses the order. Thus, to retrieve scores in ascending order: @@ -173,7 +173,7 @@ curl --request GET \ --data-urlencode 'where={"playerName":"Jonathan Walsh"}' \ --data-urlencode 'count=1' \ --data-urlencode 'limit=0' - + Response: { "results": [], @@ -308,12 +308,12 @@ The response from batch will be a list with the same number of elements as the i ### Sandbox -Before use the production database you can use the sanbox environnement. +Before use the production database you can use the sanbox environnement. For that two changes should be done : -* Every endpoint uri is `https://connect-project.io/parse-sandbox` instead of `https://connect-project.io/parse` -* Change the header value `x-parse-application-id` to `connect-sandbox`. +- Every endpoint uri is `https://connect-project.io/parse-sandbox` instead of `https://connect-project.io/parse` +- Change the header value `x-parse-application-id` to `connect-sandbox`. For the authentification you have to use the APP_TOKEN_SANDBOX instead of the APP_TOKEN. diff --git a/prod_deploy/docker-compose.yml b/prod_deploy/docker-compose.yml index b49f6b4..e4e4923 100644 --- a/prod_deploy/docker-compose.yml +++ b/prod_deploy/docker-compose.yml @@ -1,19 +1,19 @@ -version: "3" +version: '3' services: connect: image: criconnect/connect:$VERSION_NUMBER ports: - - "3000:3000" + - '3000:3000' restart: always env_file: - .env connect-sandbox: image: criconnect/connect:$VERSION_NUMBER - command: ["yarn", "start.sandbox"] + command: ['yarn', 'start.sandbox'] ports: - - "3001:3001" + - '3001:3001' restart: always env_file: - .env diff --git a/spec/api/services/application/index.spec.js b/spec/api/services/application/index.spec.js index 1176e4c..5ea561c 100644 --- a/spec/api/services/application/index.spec.js +++ b/spec/api/services/application/index.spec.js @@ -11,11 +11,13 @@ jest.mock(`${SPEC_PATH}/../src/db/model`, () => { return { Application: jest.fn().mockImplementation(() => applicationModelMock), }; - } + }; }); -jest.mock(`${SPEC_PATH}/../src/api/services/application/naming`, () => jest.fn().mockImplementation(() => applicationNamingMock)); +jest.mock(`${SPEC_PATH}/../src/api/services/application/naming`, () => + jest.fn().mockImplementation(() => applicationNamingMock), +); jest.mock('uuid/v4', () => jest.fn().mockReturnValue('uuidv4')); -jest.mock(`${SPEC_PATH}/../src/parse`, () => parseMock) +jest.mock(`${SPEC_PATH}/../src/parse`, () => parseMock); const ApplicationService = require(`${SPEC_PATH}/../src/api/services/application`); describe('Application Service', () => { @@ -24,21 +26,23 @@ describe('Application Service', () => { name: 'monApp', description: 'blabla', apple_store_link: 'http://apple.fr', - google_market_link: 'http://google.fr' - } + google_market_link: 'http://google.fr', + }; applicationNamingMock.getUniqName.mockReturnValue('12345-monapp'); - applicationModelMock.save.mockReturnValue(Promise.resolve({ - developer: { - _id: 1 - }, - name: input.name, - description: input.description, - parse_name: '12345-monapp', - token: 'uuidv4', - apple_store_link: input.apple_store_link, - google_market_link: input.google_market_link, - })) + applicationModelMock.save.mockReturnValue( + Promise.resolve({ + developer: { + _id: 1, + }, + name: input.name, + description: input.description, + parse_name: '12345-monapp', + token: 'uuidv4', + apple_store_link: input.apple_store_link, + google_market_link: input.google_market_link, + }), + ); const applicationService = new ApplicationService(); await applicationService.create({ _id: 1 }, input); diff --git a/spec/api/services/application/naming.spec.js b/spec/api/services/application/naming.spec.js index 327f93c..1971701 100644 --- a/spec/api/services/application/naming.spec.js +++ b/spec/api/services/application/naming.spec.js @@ -8,7 +8,7 @@ jest.mock(`${SPEC_PATH}/../src/db/model`, () => { return { Application: applicationModelMock, }; - } + }; }); const Naming = require(`${SPEC_PATH}/../src/api/services/application/naming`); diff --git a/spec/api/services/auth/github.spec.js b/spec/api/services/auth/github.spec.js index 1ac24fb..45efa1f 100644 --- a/spec/api/services/auth/github.spec.js +++ b/spec/api/services/auth/github.spec.js @@ -1,5 +1,5 @@ /* eslint-disable */ -const axiosMock = jest.fn() +const axiosMock = jest.fn(); jest.mock('axios', () => axiosMock); const configMock = require(`${SPEC_PATH}/__mock__/config`); @@ -10,9 +10,9 @@ describe('Github Service', () => { it('get an access token', async () => { axiosMock.mockReturnValue({ data: { - access_token: 'theAccessToken' - } - }) + access_token: 'theAccessToken', + }, + }); const accessToken = await Github.getAccessToken('anyOauthCode'); expect(accessToken).toBe('theAccessToken'); @@ -21,9 +21,9 @@ describe('Github Service', () => { it('get an user', async () => { axiosMock.mockReturnValue({ data: { - name: 'githubName' - } - }) + name: 'githubName', + }, + }); const githubUser = await Github.getUser('theAccessToken'); expect(githubUser.name).toBe('githubName'); diff --git a/spec/helper.js b/spec/helper.js index 8496284..cee45d0 100644 --- a/spec/helper.js +++ b/spec/helper.js @@ -31,27 +31,29 @@ function bindServer() { } try { const event = new EventEmitter(); - ConnectServer.start(configMock.APP_PORT, event).then(connectServer => { - server = connectServer; - let expressFinish = false; - let parseInit = false; - - event.once('parse-init', function(Parse) { - parse = Parse; - parseInit = true; - if (parseInit && expressFinish) { - resolve(); - } - }); - - server.server.once('listening', function() { - expressFinish = true; - - if (parseInit && expressFinish) { - resolve(); - } - }); - }); + ConnectServer.start(configMock.APP_PORT, event).then( + (connectServer) => { + server = connectServer; + let expressFinish = false; + let parseInit = false; + + event.once('parse-init', function (Parse) { + parse = Parse; + parseInit = true; + if (parseInit && expressFinish) { + resolve(); + } + }); + + server.server.once('listening', function () { + expressFinish = true; + + if (parseInit && expressFinish) { + resolve(); + } + }); + }, + ); } catch (error) { return reject(error); } @@ -97,7 +99,7 @@ function bindServer() { }); afterEach(async () => { - return new Promise(resolve => { + return new Promise((resolve) => { if (!server) { resolve(); } @@ -120,15 +122,12 @@ function bindGithub() { access_token: 'test-access-token', }); - nock(`https://api.github.com`) - .persist() - .get('/user') - .reply(200, { - login: 'user', - id: 1, - company: 'tester', - email: 'noreply@sample.fr', - }); + nock(`https://api.github.com`).persist().get('/user').reply(200, { + login: 'user', + id: 1, + company: 'tester', + email: 'noreply@sample.fr', + }); }); afterEach(() => nock.cleanAll()); diff --git a/spec/jest.config.js b/spec/jest.config.js index ebc35a1..d091551 100644 --- a/spec/jest.config.js +++ b/spec/jest.config.js @@ -7,8 +7,8 @@ module.exports = { '!/src/front/**/*.js', '/src/**/*.js', ], - "globals": { - "SPEC_PATH": __dirname + globals: { + SPEC_PATH: __dirname, }, - preset: '@shelf/jest-mongodb' + preset: '@shelf/jest-mongodb', }; diff --git a/src/api/controller/application.js b/src/api/controller/application.js index a31054b..17a5bb9 100644 --- a/src/api/controller/application.js +++ b/src/api/controller/application.js @@ -1,6 +1,6 @@ const ApplicationService = require('../services/application'); const createValidator = require('./validator/applicationCreate'); -const logger = require('./../../logger'); +const logger = require('../../logger'); module.exports = { list: async (req, res) => { diff --git a/src/api/controller/auth.js b/src/api/controller/auth.js index 6a5a587..13e31c2 100644 --- a/src/api/controller/auth.js +++ b/src/api/controller/auth.js @@ -1,5 +1,5 @@ -const Auth = require('./../services/auth'); -const logger = require('./../../logger'); +const Auth = require('../services/auth'); +const logger = require('../../logger'); module.exports = { github: async (req, res) => { diff --git a/src/api/controller/developer.js b/src/api/controller/developer.js index 5f2eba7..5a5e998 100644 --- a/src/api/controller/developer.js +++ b/src/api/controller/developer.js @@ -1,5 +1,5 @@ const DeveloperService = require('../services/developer'); -const logger = require('./../../logger'); +const logger = require('../../logger'); module.exports = { delete: async (req, res) => { diff --git a/src/api/controller/validator/applicationCreate.js b/src/api/controller/validator/applicationCreate.js index eab146d..5d26287 100644 --- a/src/api/controller/validator/applicationCreate.js +++ b/src/api/controller/validator/applicationCreate.js @@ -1,6 +1,6 @@ const validate = require('validate.js'); -module.exports = data => +module.exports = (data) => validate(data, { name: { presence: true, diff --git a/src/api/index.js b/src/api/index.js index f8e2b1e..cb8c27f 100644 --- a/src/api/index.js +++ b/src/api/index.js @@ -4,7 +4,7 @@ const authController = require('./controller/auth'); const applicationController = require('./controller/application'); const developerController = require('./controller/developer'); -module.exports = srv => { +module.exports = (srv) => { srv.use('/api/*', authMiddleware); srv.use('/api/*', aclMiddleware); diff --git a/src/api/middleware/acl.js b/src/api/middleware/acl.js index 577c17e..12bd1e5 100644 --- a/src/api/middleware/acl.js +++ b/src/api/middleware/acl.js @@ -1,4 +1,4 @@ -const logger = require('./../../logger'); +const logger = require('../../logger'); module.exports = async (req, res, next) => { try { diff --git a/src/api/middleware/auth.js b/src/api/middleware/auth.js index 6f17ac2..8bc25e5 100644 --- a/src/api/middleware/auth.js +++ b/src/api/middleware/auth.js @@ -1,14 +1,14 @@ const jwt = require('jsonwebtoken'); const { promisify } = require('util'); -const logger = require('./../../logger'); -const { AUTH_SECRET } = require('./../../config'); -const mongoModel = require('./../../db/model'); +const logger = require('../../logger'); +const { AUTH_SECRET } = require('../../config'); +const mongoModel = require('../../db/model'); const jwtVerify = promisify(jwt.verify); const bearerLength = 'Bearer '.length; -const getTokenFromAuthHeader = header => { +const getTokenFromAuthHeader = (header) => { if (header && header.length > bearerLength) { return header.slice(bearerLength); } diff --git a/src/api/services/application/index.js b/src/api/services/application/index.js index 3756da4..69794f1 100644 --- a/src/api/services/application/index.js +++ b/src/api/services/application/index.js @@ -1,8 +1,8 @@ const uuidv4 = require('uuid/v4'); -const Parse = require('./../../../parse'); +const Parse = require('../../../parse'); const Naming = require('./naming'); -const mongoModel = require('./../../../db/model'); -const { PARSE_SANDBOX } = require('./../../../config'); +const mongoModel = require('../../../db/model'); +const { PARSE_SANDBOX } = require('../../../config'); class Application { constructor() { diff --git a/src/api/services/application/naming.js b/src/api/services/application/naming.js index 38195dc..4461467 100644 --- a/src/api/services/application/naming.js +++ b/src/api/services/application/naming.js @@ -1,4 +1,4 @@ -const mongoModel = require('./../../../db/model'); +const mongoModel = require('../../../db/model'); class Naming { constructor() { diff --git a/src/api/services/auth/github.js b/src/api/services/auth/github.js index 38b4da8..f9c5cea 100644 --- a/src/api/services/auth/github.js +++ b/src/api/services/auth/github.js @@ -1,5 +1,5 @@ const axios = require('axios'); -const { GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET } = require('./../../../config'); +const { GITHUB_CLIENT_ID, GITHUB_CLIENT_SECRET } = require('../../../config'); class Github { static async getAccessToken(code) { diff --git a/src/api/services/auth/index.js b/src/api/services/auth/index.js index d20e661..1dcb6be 100644 --- a/src/api/services/auth/index.js +++ b/src/api/services/auth/index.js @@ -2,7 +2,7 @@ const jwt = require('jsonwebtoken'); const moment = require('moment'); const { AUTH_SECRET } = require('../../../config'); const Github = require('./github'); -const mongoModel = require('./../../../db/model'); +const mongoModel = require('../../../db/model'); class Auth { constructor() { @@ -47,9 +47,7 @@ class Auth { name, id: developer.github_id, iat: moment().valueOf(), - exp: moment() - .add(1, 'days') - .valueOf(), + exp: moment().add(1, 'days').valueOf(), }, AUTH_SECRET, ); diff --git a/src/api/services/developer/clearParse.js b/src/api/services/developer/clearParse.js index 29d9e92..48ffec8 100644 --- a/src/api/services/developer/clearParse.js +++ b/src/api/services/developer/clearParse.js @@ -1,6 +1,6 @@ -const getParseModel = require('./../../../db/parse'); -const getClasses = require('./../../../parse/schema/getClasses'); -const logger = require('./../../../logger'); +const getParseModel = require('../../../db/parse'); +const getClasses = require('../../../parse/schema/getClasses'); +const logger = require('../../../logger'); // Remove all data related to an application (user in parse) async function clearParseUser(username, sandbox) { diff --git a/src/api/services/developer/index.js b/src/api/services/developer/index.js index 923e875..36d09c2 100644 --- a/src/api/services/developer/index.js +++ b/src/api/services/developer/index.js @@ -1,6 +1,6 @@ -const mongoModel = require('./../../../db/model'); +const mongoModel = require('../../../db/model'); const clearParseUser = require('./clearParse'); -const { PARSE_SANDBOX } = require('./../../../config'); +const { PARSE_SANDBOX } = require('../../../config'); class Developer { constructor() { diff --git a/src/db/model/application.js b/src/db/model/application.js index ce45a46..b8ed426 100644 --- a/src/db/model/application.js +++ b/src/db/model/application.js @@ -1,6 +1,6 @@ const mongoose = require('mongoose'); -module.exports = apiConnect => { +module.exports = (apiConnect) => { if (apiConnect.modelNames().includes('Application')) { return apiConnect.model('Application'); } diff --git a/src/db/model/developer.js b/src/db/model/developer.js index 6275bb6..3ec0926 100644 --- a/src/db/model/developer.js +++ b/src/db/model/developer.js @@ -1,6 +1,6 @@ const mongoose = require('mongoose'); -module.exports = apiConnect => { +module.exports = (apiConnect) => { if (apiConnect.modelNames().includes('Developer')) { return apiConnect.model('Developer'); } diff --git a/src/db/parse.js b/src/db/parse.js index fc6426c..d7132cd 100644 --- a/src/db/parse.js +++ b/src/db/parse.js @@ -1,5 +1,5 @@ const mongoose = require('mongoose'); -const getClasses = require('./../parse/schema/getClasses'); +const getClasses = require('../parse/schema/getClasses'); const connectClient = require('./client'); const modelMapping = new Map(); diff --git a/src/front/component/App.jsx b/src/front/component/App.jsx index 94d612f..7352ece 100644 --- a/src/front/component/App.jsx +++ b/src/front/component/App.jsx @@ -159,6 +159,7 @@ class App extends React.PureComponent { > {({ TransitionProps, placement }) => ( - this.handleMenuItemClick(event, index) - } + this.handleMenuItemClick(event, index)} > {option} diff --git a/src/front/index.css b/src/front/index.css index d701104..3104449 100644 --- a/src/front/index.css +++ b/src/front/index.css @@ -10,4 +10,4 @@ a { .spacer { flex: 1; -} \ No newline at end of file +} diff --git a/src/front/pages/details/details.jsx b/src/front/pages/details/details.jsx index 801791c..f0431da 100644 --- a/src/front/pages/details/details.jsx +++ b/src/front/pages/details/details.jsx @@ -77,8 +77,8 @@ class DetailsPage extends React.PureComponent { componentDidMount() { const { match } = this.props; - getApplication(match.params.appId).then(res => { - this.setState(prevState => { + getApplication(match.params.appId).then((res) => { + this.setState((prevState) => { return { ...prevState, loading: false, @@ -140,7 +140,7 @@ class DetailsPage extends React.PureComponent { copyToClipboard(key) { const { application } = this.state; - navigator.permissions.query({ name: 'clipboard-write' }).then(result => { + navigator.permissions.query({ name: 'clipboard-write' }).then((result) => { if (result.state === 'granted' || result.state === 'prompt') { navigator.clipboard.writeText(application[key]); this.setState({ snackBarOpen: true }); @@ -170,7 +170,7 @@ class DetailsPage extends React.PureComponent { className={classes.textField} fullWidth value={application.name} - onChange={event => this.handleChange('name', event)} + onChange={(event) => this.handleChange('name', event)} margin="normal" variant="outlined" error={errors.name} @@ -182,7 +182,7 @@ class DetailsPage extends React.PureComponent { className={classes.textField} fullWidth value={application.description} - onChange={event => this.handleChange('description', event)} + onChange={(event) => this.handleChange('description', event)} margin="normal" variant="outlined" multiline @@ -196,7 +196,8 @@ class DetailsPage extends React.PureComponent { className={classes.textField} fullWidth value={application.apple_store_link || ''} - onChange={event => this.handleChange('apple_store_link', event)} + onChange={(event) => + this.handleChange('apple_store_link', event)} margin="normal" variant="outlined" error={errors.apple_store_link} @@ -208,9 +209,8 @@ class DetailsPage extends React.PureComponent { className={classes.textField} fullWidth value={application.google_market_link || ''} - onChange={event => - this.handleChange('google_market_link', event) - } + onChange={(event) => + this.handleChange('google_market_link', event)} margin="normal" variant="outlined" error={errors.google_market_link} diff --git a/src/front/pages/home/home.jsx b/src/front/pages/home/home.jsx index c84026a..cc16309 100644 --- a/src/front/pages/home/home.jsx +++ b/src/front/pages/home/home.jsx @@ -87,7 +87,7 @@ class HomePage extends React.PureComponent { } componentDidMount() { - listOfApplications().then(res => { + listOfApplications().then((res) => { this.setState({ loading: false, developerApplications: res, @@ -165,7 +165,7 @@ class HomePage extends React.PureComponent { {loading && } {!loading && - developerApplications.map(application => ( + developerApplications.map((application) => (
+ <> {application.name} - + } secondary={application.description} /> @@ -245,7 +245,7 @@ class HomePage extends React.PureComponent { className={classes.textField} fullWidth value={newApplication.name} - onChange={event => this.handleChange('name', event)} + onChange={(event) => this.handleChange('name', event)} margin="normal" variant="outlined" error={errors.name} @@ -258,7 +258,7 @@ class HomePage extends React.PureComponent { className={classes.textField} fullWidth value={newApplication.description} - onChange={event => this.handleChange('description', event)} + onChange={(event) => this.handleChange('description', event)} margin="normal" variant="outlined" multiline @@ -272,7 +272,7 @@ class HomePage extends React.PureComponent { className={classes.textField} fullWidth value={newApplication.apple_store_link} - onChange={event => this.handleChange('apple_store_link', event)} + onChange={(event) => this.handleChange('apple_store_link', event)} margin="normal" variant="outlined" error={errors.apple_store_link} @@ -284,7 +284,8 @@ class HomePage extends React.PureComponent { className={classes.textField} fullWidth value={newApplication.google_market_link} - onChange={event => this.handleChange('google_market_link', event)} + onChange={(event) => + this.handleChange('google_market_link', event)} margin="normal" variant="outlined" error={errors.google_market_link} diff --git a/src/front/pages/profile/profile.jsx b/src/front/pages/profile/profile.jsx index a3e6247..3a07ce0 100644 --- a/src/front/pages/profile/profile.jsx +++ b/src/front/pages/profile/profile.jsx @@ -123,7 +123,7 @@ class ProfilePage extends React.PureComponent { className={classes.textField} fullWidth value={user.name} - onChange={event => this.handleChange('name', event)} + onChange={(event) => this.handleChange('name', event)} margin="normal" variant="outlined" /> @@ -135,7 +135,7 @@ class ProfilePage extends React.PureComponent { className={classes.textField} fullWidth value={user.login} - onChange={event => this.handleChange('githubLogin', event)} + onChange={(event) => this.handleChange('githubLogin', event)} margin="normal" variant="outlined" /> diff --git a/src/front/registerServiceWorker.jsx b/src/front/registerServiceWorker.jsx index a8cc8a1..5294c90 100644 --- a/src/front/registerServiceWorker.jsx +++ b/src/front/registerServiceWorker.jsx @@ -59,7 +59,7 @@ export default function register() { function registerValidSW(swUrl) { navigator.serviceWorker .register(swUrl) - .then(registration => { + .then((registration) => { registration.onupdatefound = () => { const installingWorker = registration.installing; if (installingWorker) { @@ -82,7 +82,7 @@ function registerValidSW(swUrl) { } }; }) - .catch(error => { + .catch((error) => { console.error('Error during service worker registration:', error); }); } @@ -90,14 +90,14 @@ function registerValidSW(swUrl) { function checkValidServiceWorker(swUrl) { // Check if the service worker can be found. If it can't reload the page. fetch(swUrl) - .then(response => { + .then((response) => { // Ensure service worker exists, and that we really are getting a JS file. if ( response.status === 404 || response.headers.get('content-type').indexOf('javascript') === -1 ) { // No service worker found. Probably a different app. Reload the page. - navigator.serviceWorker.ready.then(registration => { + navigator.serviceWorker.ready.then((registration) => { registration.unregister().then(() => { window.location.reload(); }); @@ -116,7 +116,7 @@ function checkValidServiceWorker(swUrl) { export function unregister() { if ('serviceWorker' in navigator) { - navigator.serviceWorker.ready.then(registration => { + navigator.serviceWorker.ready.then((registration) => { registration.unregister(); }); } diff --git a/src/front/services/api.jsx b/src/front/services/api.jsx index d84a531..3159ffb 100644 --- a/src/front/services/api.jsx +++ b/src/front/services/api.jsx @@ -34,7 +34,7 @@ export const listOfApplications = async () => { /* Returns details of one application */ -export const getApplication = async appId => { +export const getApplication = async (appId) => { const headers = headersWithJWT(); if (!headers) { return {}; @@ -53,7 +53,7 @@ export const getApplication = async appId => { /* Create a new application on the connected user */ -export const createApplication = async newApplication => { +export const createApplication = async (newApplication) => { const headers = headersWithJWT(); if (!headers) { return {}; diff --git a/src/front/services/auth.jsx b/src/front/services/auth.jsx index c555707..c3126d1 100644 --- a/src/front/services/auth.jsx +++ b/src/front/services/auth.jsx @@ -9,7 +9,7 @@ export const logout = () => { Cookie.remove(COOKIENAME); }; -const isJwtValid = jwt => { +const isJwtValid = (jwt) => { if (!jwt) { return false; } @@ -32,7 +32,7 @@ const isJwtValid = jwt => { return now < exp; }; -export const setAuthToken = token => { +export const setAuthToken = (token) => { if (!isJwtValid(token)) { connectedState.next(false); return false; diff --git a/src/front/services/formValidator.jsx b/src/front/services/formValidator.jsx index a5eb968..75439a2 100644 --- a/src/front/services/formValidator.jsx +++ b/src/front/services/formValidator.jsx @@ -30,9 +30,9 @@ export const validateFormField = (value, field) => { return validated; }; -export const checkValid = errorState => { +export const checkValid = (errorState) => { let valid = true; - Object.keys(errorState).forEach(element => { + Object.keys(errorState).forEach((element) => { if (errorState[element] === true) { valid = false; } diff --git a/src/logger.js b/src/logger.js index 620d35a..713f0c0 100644 --- a/src/logger.js +++ b/src/logger.js @@ -60,7 +60,7 @@ function createFormatMessage(name) { * @param {*} severity */ function addSeverity(severity) { - return params => ({ + return (params) => ({ ...params, severity, }); diff --git a/src/middleware/parse.js b/src/middleware/parse.js index fb0083d..7e34715 100644 --- a/src/middleware/parse.js +++ b/src/middleware/parse.js @@ -8,8 +8,8 @@ const { PARSE_MASTER_KEY, PARSE_READONLY_MASTER_KEY, PARSE_SILENT, -} = require('./../config'); -const cloud = require('./../parse/cloud/main'); +} = require('../config'); +const cloud = require('../parse/cloud/main'); class ParseMiddelware { constructor(app) { @@ -17,10 +17,10 @@ class ParseMiddelware { } static start(options, parseCloudEvent) { - return new Promise(resolve => { + return new Promise((resolve) => { let parseMiddelware; const parseOptions = Object.assign(options, { - cloud: Parse => { + cloud: (Parse) => { cloud(Parse, parseCloudEvent); }, serverStartComplete: () => { @@ -34,7 +34,7 @@ class ParseMiddelware { } } -module.exports = parseCloudEvent => +module.exports = (parseCloudEvent) => ParseMiddelware.start( { databaseURI: MONGO_URI, diff --git a/src/middleware/parseDashboard.js b/src/middleware/parseDashboard.js index 73b7cb2..4f573d3 100644 --- a/src/middleware/parseDashboard.js +++ b/src/middleware/parseDashboard.js @@ -12,7 +12,7 @@ const { PARSE_READONLY_MASTER_KEY, PARSE_DASHBOARD_MAINTENER_PWD, PARSE_DASHBOARD_ROOT_PWD, -} = require('./../config'); +} = require('../config'); module.exports = () => new ParseDashboard({ diff --git a/src/middleware/parseSandbox.js b/src/middleware/parseSandbox.js index 1cab8e3..edb5a8d 100644 --- a/src/middleware/parseSandbox.js +++ b/src/middleware/parseSandbox.js @@ -7,7 +7,7 @@ const { PARSE_FILE_KEY, PARSE_MASTER_KEY, PARSE_READONLY_MASTER_KEY, -} = require('./../config'); +} = require('../config'); module.exports = () => new ParseServer({ diff --git a/src/middleware/parseSwagger.js b/src/middleware/parseSwagger.js index 47dc897..604758a 100644 --- a/src/middleware/parseSwagger.js +++ b/src/middleware/parseSwagger.js @@ -1,5 +1,5 @@ const ParseSwagger = require('../parse/parse-server-swagger'); -const { PARSE_APP_ID, PARSE_MASTER_KEY, API_URL } = require('./../config'); +const { PARSE_APP_ID, PARSE_MASTER_KEY, API_URL } = require('../config'); module.exports = () => new ParseSwagger({ diff --git a/src/parse/cloud/main.js b/src/parse/cloud/main.js index 5d5a40f..13a2846 100644 --- a/src/parse/cloud/main.js +++ b/src/parse/cloud/main.js @@ -1,5 +1,5 @@ /* eslint-disable no-undef */ -const logger = require('./../../logger'); +const logger = require('../../logger'); const schemaSync = require('../schema/sync'); const roleInstall = require('../role/install'); const roleGet = require('../role/get'); @@ -20,7 +20,7 @@ async function init(Parse) { } module.exports = (Parse, event) => { - Parse.Cloud.afterSave(Parse.User, async req => { + Parse.Cloud.afterSave(Parse.User, async (req) => { if (req.object.existed()) { return null; } @@ -49,5 +49,5 @@ module.exports = (Parse, event) => { } logger.info(`Parse correctly init`); }) - .catch(err => logger.info(`Issue to init Parse : ${err}`)); + .catch((err) => logger.info(`Issue to init Parse : ${err}`)); }; diff --git a/src/parse/cloud/setAfterFind.js b/src/parse/cloud/setAfterFind.js index 5c6575c..3058d00 100644 --- a/src/parse/cloud/setAfterFind.js +++ b/src/parse/cloud/setAfterFind.js @@ -1,9 +1,9 @@ -const getClasses = require('./../schema/getClasses'); +const getClasses = require('../schema/getClasses'); -module.exports = async Parse => { +module.exports = async (Parse) => { const schemaClasses = await getClasses(); for (const schemaClass of schemaClasses) { - Parse.Cloud.afterFind(schemaClass.className, req => { + Parse.Cloud.afterFind(schemaClass.className, (req) => { if (req.master) { return; } diff --git a/src/parse/cloud/setAfterSave.js b/src/parse/cloud/setAfterSave.js index d1f2b08..3449c24 100644 --- a/src/parse/cloud/setAfterSave.js +++ b/src/parse/cloud/setAfterSave.js @@ -1,9 +1,9 @@ -const getClasses = require('./../schema/getClasses'); +const getClasses = require('../schema/getClasses'); -module.exports = async Parse => { +module.exports = async (Parse) => { const schemaClasses = await getClasses(); for (const schemaClass of schemaClasses) { - Parse.Cloud.afterSave(schemaClass.className, req => { + Parse.Cloud.afterSave(schemaClass.className, (req) => { const jsonObject = req.object.toJSON(); delete jsonObject.owner; delete jsonObject.ACL; diff --git a/src/parse/cloud/setBeforeSave.js b/src/parse/cloud/setBeforeSave.js index a23e24c..072c27b 100644 --- a/src/parse/cloud/setBeforeSave.js +++ b/src/parse/cloud/setBeforeSave.js @@ -1,9 +1,9 @@ -const getClasses = require('./../schema/getClasses'); +const getClasses = require('../schema/getClasses'); -module.exports = async Parse => { +module.exports = async (Parse) => { const schemaClasses = await getClasses(); for (const schemaClass of schemaClasses) { - Parse.Cloud.beforeSave(schemaClass.className, req => { + Parse.Cloud.beforeSave(schemaClass.className, (req) => { if (!req.user) { return; } diff --git a/src/parse/index.js b/src/parse/index.js index 315bed0..0489e9c 100644 --- a/src/parse/index.js +++ b/src/parse/index.js @@ -4,7 +4,7 @@ const { PARSE_MASTER_KEY, API_URL, SANDBOX_URL, -} = require('./../config'); +} = require('../config'); class Parse { static async signUp(username, password, isSandbox) { diff --git a/src/parse/parse-server-swagger/index.js b/src/parse/parse-server-swagger/index.js index 7f7b60e..2da1643 100644 --- a/src/parse/parse-server-swagger/index.js +++ b/src/parse/parse-server-swagger/index.js @@ -1,56 +1,56 @@ -// All credit to https://github.com/bhtz/parse-server-swagger -// the code is adapted for our use case - -const express = require('express'); -const swaggerUi = require('swagger-ui-express'); -const request = require('request-promise'); -const { parseSchemaToSwagger } = require('./schema-to-swagger'); -const parseBaseSwaggerSpec = require('./parse-swagger-base.json'); - -/** - * constructor - * @returns app: express middleware - */ -function ParseSwagger(options) { - this.config = options; - - const app = express(); - - const swagOpts = { swaggerUrl: `${this.config.host}/api-docs` }; - app.use('/swagger', swaggerUi.serve, swaggerUi.setup(null, swagOpts)); - app.use('/api-docs', this.renderSwaggerSpec.bind(this)); - - return app; -} - -/** - * Get parse compatible api swagger.json base - */ -ParseSwagger.prototype.renderSwaggerSpec = (_, res) => { - const options = { - url: `${this.config.host} ${this.config.apiRoot}/schemas`, - method: 'GET', - json: true, - headers: { - 'X-Parse-Application-Id': this.config.appId, - 'X-Parse-Master-Key': this.config.masterKey, - }, - }; - - const excludes = this.config.excludes || []; - - request(options) - .then(data => { - const swagger = parseSchemaToSwagger( - parseBaseSwaggerSpec, - data.results, - excludes, - ); - res.json(swagger); - }) - .catch(error => { - res.send(`Request failed with response code ${error.statu}`); - }); -}; - -module.exports = ParseSwagger; +// All credit to https://github.com/bhtz/parse-server-swagger +// the code is adapted for our use case + +const express = require('express'); +const swaggerUi = require('swagger-ui-express'); +const request = require('request-promise'); +const { parseSchemaToSwagger } = require('./schema-to-swagger'); +const parseBaseSwaggerSpec = require('./parse-swagger-base.json'); + +/** + * constructor + * @returns app: express middleware + */ +function ParseSwagger(options) { + this.config = options; + + const app = express(); + + const swagOpts = { swaggerUrl: `${this.config.host}/api-docs` }; + app.use('/swagger', swaggerUi.serve, swaggerUi.setup(null, swagOpts)); + app.use('/api-docs', this.renderSwaggerSpec.bind(this)); + + return app; +} + +/** + * Get parse compatible api swagger.json base + */ +ParseSwagger.prototype.renderSwaggerSpec = (_, res) => { + const options = { + url: `${this.config.host} ${this.config.apiRoot}/schemas`, + method: 'GET', + json: true, + headers: { + 'X-Parse-Application-Id': this.config.appId, + 'X-Parse-Master-Key': this.config.masterKey, + }, + }; + + const excludes = this.config.excludes || []; + + request(options) + .then((data) => { + const swagger = parseSchemaToSwagger( + parseBaseSwaggerSpec, + data.results, + excludes, + ); + res.json(swagger); + }) + .catch((error) => { + res.send(`Request failed with response code ${error.statu}`); + }); +}; + +module.exports = ParseSwagger; diff --git a/src/parse/parse-server-swagger/parse-swagger-base.json b/src/parse/parse-server-swagger/parse-swagger-base.json index 88935e5..3466947 100644 --- a/src/parse/parse-server-swagger/parse-swagger-base.json +++ b/src/parse/parse-server-swagger/parse-swagger-base.json @@ -1,61 +1,61 @@ -{ - "swagger": "2.0", - "info": { - "title": "Connect API", - "description": "Full API documentation of the connect api", - "version": "1.0.0" - }, - "schemes": ["http", "https"], - "securityDefinitions": { - "ParseAppId": { - "type": "apiKey", - "name": "X-Parse-Application-Id", - "in": "header" - }, - "ParseSessionId": { - "type": "apiKey", - "name": "X-Parse-Session-Token", - "in": "header" - } - }, - "basePath": "/", - "produces": ["application/json"], - "components": { - "schemas": { - "Batch": { - "type": "object", - "properties": { - "requests": { - "type": "array", - "items": { - "type": "object", - "properties": { - "method": { - "type": "string" - }, - "path": { - "type": "string" - }, - "body": { - "type": "object" - } - } - } - } - } - }, - "notfound": { - "type": "object", - "properties": { - "code": { - "type": "string" - }, - "error": { - "type": "string" - } - } - } - } - }, - "paths": {} -} +{ + "swagger": "2.0", + "info": { + "title": "Connect API", + "description": "Full API documentation of the connect api", + "version": "1.0.0" + }, + "schemes": ["http", "https"], + "securityDefinitions": { + "ParseAppId": { + "type": "apiKey", + "name": "X-Parse-Application-Id", + "in": "header" + }, + "ParseSessionId": { + "type": "apiKey", + "name": "X-Parse-Session-Token", + "in": "header" + } + }, + "basePath": "/", + "produces": ["application/json"], + "components": { + "schemas": { + "Batch": { + "type": "object", + "properties": { + "requests": { + "type": "array", + "items": { + "type": "object", + "properties": { + "method": { + "type": "string" + }, + "path": { + "type": "string" + }, + "body": { + "type": "object" + } + } + } + } + } + }, + "notfound": { + "type": "object", + "properties": { + "code": { + "type": "string" + }, + "error": { + "type": "string" + } + } + } + } + }, + "paths": {} +} diff --git a/src/parse/parse-server-swagger/schema-to-swagger.js b/src/parse/parse-server-swagger/schema-to-swagger.js index 8c9c127..cf73ca8 100644 --- a/src/parse/parse-server-swagger/schema-to-swagger.js +++ b/src/parse/parse-server-swagger/schema-to-swagger.js @@ -1,272 +1,272 @@ -/** - * Cast parse type to swagger type - * @param {Parse type} type - */ -function schemaTypeToSwaggerType(type) { - let swaggerType; - switch (type) { - case 'String': - swaggerType = { type: 'string' }; - break; - - case 'Number': - swaggerType = { type: 'number' }; - break; - - case 'Boolean': - swaggerType = { type: 'boolean' }; - break; - - case 'Array': - swaggerType = { type: 'array', items: { type: 'object' } }; - break; - - case 'Object': - swaggerType = { type: 'object' }; - break; - - case 'File': - swaggerType = { type: 'object' }; - break; - - case 'Pointer': - swaggerType = { type: 'object' }; - break; - - case 'Relation': - swaggerType = { type: 'object' }; - break; - - default: - swaggerType = { type: 'string' }; - break; - } - return swaggerType; -} - -/** - * Get swagger configuration (CREATE, READ) for parse endpoint - * @param {*} classes - */ -function getPath(classes) { - return { - get: { - security: [{ ParseAppId: [], ParseSessionId: [] }], - summary: `Get ${classes.className} data`, - description: - 'Find queries documentation here https://docs.parseplatform.org/rest/guide/#queries', - tags: [`${classes.className}`], - responses: { - '200': { - description: `Return ${classes.className} data`, - schema: { - $ref: `#/components/schemas/${classes.className}`, - }, - }, - '400': { description: 'Bad Request' }, - '401': { description: 'Unauthorized' }, - '406': { description: 'Not Acceptable' }, - '500': { description: 'Server Internal error' }, - }, - }, - post: { - security: [{ ParseAppId: [], ParseSessionId: [] }], - summary: 'Add object instance', - description: 'Happy to access The System', - tags: [`${classes.className}`], - parameters: [ - { - in: 'body', - name: 'body', - description: 'object that needs to be added to the store', - required: true, - schema: { - $ref: `#/components/schemas/${classes.className}`, - }, - }, - ], - responses: { - '200': { - description: `Returns ${classes.className} data`, - schema: { - $ref: `#/components/schemas/${classes.className}`, - }, - }, - '400': { description: 'Bad Request' }, - '401': { description: 'Unauthorized' }, - '406': { description: 'Not Acceptable' }, - '500': { description: 'Server Internal error' }, - }, - }, - }; -} - -/** - * Get swagger configuration (UPDATE, READ, DELETE) for parse endpoint - * @param {*} classes - */ -function getPathById(classes) { - return { - get: { - security: [ - { - ParseAppId: [], - ParseSessionId: [], - }, - ], - summary: `Get ${classes.className} by id`, - description: 'Happy to access The System', - tags: [`${classes.className}`], - parameters: [ - { - in: 'path', - name: 'id', - type: 'string', - description: 'The id of the element you want to get.', - required: true, - }, - ], - responses: { - '200': { - description: 'Returns data', - schema: { - $ref: `#/components/schemas/${classes.className}`, - }, - }, - '400': { description: 'Bad Request' }, - '401': { description: 'Unauthorized' }, - '406': { description: 'Not Acceptable' }, - '500': { description: 'Server Internal error' }, - }, - }, - put: { - security: [ - { - ParseAppId: [], - ParseSessionId: [], - }, - ], - summary: 'Update instance', - description: 'Happy to access The System', - tags: [`${classes.className}`], - parameters: [ - { - in: 'path', - name: 'id', - type: 'string', - description: 'The id of the element you want to update.', - required: true, - }, - { - in: 'body', - name: 'movie', - description: 'The element you want update with.', - required: true, - schema: { - $ref: `#/components/schemas/${classes.className}`, - }, - }, - ], - responses: { - '200': { - description: 'Returns instance data', - schema: { - $ref: `#/components/schemas/${classes.className}`, - }, - }, - '400': { - description: 'Bad Request', - }, - '401': { - description: 'Unauthorized', - }, - '406': { - description: 'Not Acceptable', - }, - '500': { - description: 'Server Internal error', - }, - }, - }, - delete: { - security: [ - { - ParseAppId: [], - ParseSessionId: [], - }, - ], - summary: 'Delete instance', - description: 'Happy to access The System', - tags: [`${classes.className}`], - parameters: [ - { - in: 'path', - name: 'id', - type: 'string', - description: 'The id of the element you want to delete.', - required: true, - }, - ], - responses: { - '200': { - description: 'Returns a confirmation message', - }, - '400': { - description: 'Bad Request', - }, - '401': { - description: 'Unauthorized', - }, - '404': { - description: 'Id not found', - schema: { - $ref: '#/components/schemas/notfound', - }, - }, - '406': { - description: 'Not Acceptable', - }, - '500': { - description: 'Server Internal error', - }, - }, - }, - }; -} - -/** - * - * @param {classe} parse server classes - */ -function transformClasseToSchema(classe) { - const schema = { type: 'object', properties: {} }; - - classe.forEach((element, key) => { - if (key !== 'ACL') { - schema.properties[key] = schemaTypeToSwaggerType(element.type); - } - }); - - return schema; -} - -/** - * Transform Parse Server schema.json to swagger.json - */ -exports.parseSchemaToSwagger = (spec, schemas, excludes) => { - const newSpec = spec; - - for (const classes of schemas) { - if (!excludes.includes(classes.className)) { - newSpec.components.schemas[classes.className] = transformClasseToSchema( - classes, - ); - newSpec.paths[`/parse/classes/${classes.className}`] = getPath(classes); - newSpec.paths[`/parse/classes/${classes.className}/{id}`] = getPathById( - classes, - ); - } - } - - return spec; -}; +/** + * Cast parse type to swagger type + * @param {Parse type} type + */ +function schemaTypeToSwaggerType(type) { + let swaggerType; + switch (type) { + case 'String': + swaggerType = { type: 'string' }; + break; + + case 'Number': + swaggerType = { type: 'number' }; + break; + + case 'Boolean': + swaggerType = { type: 'boolean' }; + break; + + case 'Array': + swaggerType = { type: 'array', items: { type: 'object' } }; + break; + + case 'Object': + swaggerType = { type: 'object' }; + break; + + case 'File': + swaggerType = { type: 'object' }; + break; + + case 'Pointer': + swaggerType = { type: 'object' }; + break; + + case 'Relation': + swaggerType = { type: 'object' }; + break; + + default: + swaggerType = { type: 'string' }; + break; + } + return swaggerType; +} + +/** + * Get swagger configuration (CREATE, READ) for parse endpoint + * @param {*} classes + */ +function getPath(classes) { + return { + get: { + security: [{ ParseAppId: [], ParseSessionId: [] }], + summary: `Get ${classes.className} data`, + description: + 'Find queries documentation here https://docs.parseplatform.org/rest/guide/#queries', + tags: [`${classes.className}`], + responses: { + 200: { + description: `Return ${classes.className} data`, + schema: { + $ref: `#/components/schemas/${classes.className}`, + }, + }, + 400: { description: 'Bad Request' }, + 401: { description: 'Unauthorized' }, + 406: { description: 'Not Acceptable' }, + 500: { description: 'Server Internal error' }, + }, + }, + post: { + security: [{ ParseAppId: [], ParseSessionId: [] }], + summary: 'Add object instance', + description: 'Happy to access The System', + tags: [`${classes.className}`], + parameters: [ + { + in: 'body', + name: 'body', + description: 'object that needs to be added to the store', + required: true, + schema: { + $ref: `#/components/schemas/${classes.className}`, + }, + }, + ], + responses: { + 200: { + description: `Returns ${classes.className} data`, + schema: { + $ref: `#/components/schemas/${classes.className}`, + }, + }, + 400: { description: 'Bad Request' }, + 401: { description: 'Unauthorized' }, + 406: { description: 'Not Acceptable' }, + 500: { description: 'Server Internal error' }, + }, + }, + }; +} + +/** + * Get swagger configuration (UPDATE, READ, DELETE) for parse endpoint + * @param {*} classes + */ +function getPathById(classes) { + return { + get: { + security: [ + { + ParseAppId: [], + ParseSessionId: [], + }, + ], + summary: `Get ${classes.className} by id`, + description: 'Happy to access The System', + tags: [`${classes.className}`], + parameters: [ + { + in: 'path', + name: 'id', + type: 'string', + description: 'The id of the element you want to get.', + required: true, + }, + ], + responses: { + 200: { + description: 'Returns data', + schema: { + $ref: `#/components/schemas/${classes.className}`, + }, + }, + 400: { description: 'Bad Request' }, + 401: { description: 'Unauthorized' }, + 406: { description: 'Not Acceptable' }, + 500: { description: 'Server Internal error' }, + }, + }, + put: { + security: [ + { + ParseAppId: [], + ParseSessionId: [], + }, + ], + summary: 'Update instance', + description: 'Happy to access The System', + tags: [`${classes.className}`], + parameters: [ + { + in: 'path', + name: 'id', + type: 'string', + description: 'The id of the element you want to update.', + required: true, + }, + { + in: 'body', + name: 'movie', + description: 'The element you want update with.', + required: true, + schema: { + $ref: `#/components/schemas/${classes.className}`, + }, + }, + ], + responses: { + 200: { + description: 'Returns instance data', + schema: { + $ref: `#/components/schemas/${classes.className}`, + }, + }, + 400: { + description: 'Bad Request', + }, + 401: { + description: 'Unauthorized', + }, + 406: { + description: 'Not Acceptable', + }, + 500: { + description: 'Server Internal error', + }, + }, + }, + delete: { + security: [ + { + ParseAppId: [], + ParseSessionId: [], + }, + ], + summary: 'Delete instance', + description: 'Happy to access The System', + tags: [`${classes.className}`], + parameters: [ + { + in: 'path', + name: 'id', + type: 'string', + description: 'The id of the element you want to delete.', + required: true, + }, + ], + responses: { + 200: { + description: 'Returns a confirmation message', + }, + 400: { + description: 'Bad Request', + }, + 401: { + description: 'Unauthorized', + }, + 404: { + description: 'Id not found', + schema: { + $ref: '#/components/schemas/notfound', + }, + }, + 406: { + description: 'Not Acceptable', + }, + 500: { + description: 'Server Internal error', + }, + }, + }, + }; +} + +/** + * + * @param {classe} parse server classes + */ +function transformClasseToSchema(classe) { + const schema = { type: 'object', properties: {} }; + + classe.forEach((element, key) => { + if (key !== 'ACL') { + schema.properties[key] = schemaTypeToSwaggerType(element.type); + } + }); + + return schema; +} + +/** + * Transform Parse Server schema.json to swagger.json + */ +exports.parseSchemaToSwagger = (spec, schemas, excludes) => { + const newSpec = spec; + + for (const classes of schemas) { + if (!excludes.includes(classes.className)) { + newSpec.components.schemas[classes.className] = transformClasseToSchema( + classes, + ); + newSpec.paths[`/parse/classes/${classes.className}`] = getPath(classes); + newSpec.paths[`/parse/classes/${classes.className}/{id}`] = getPathById( + classes, + ); + } + } + + return spec; +}; diff --git a/src/parse/schema/classes/jsonSchemaData.js b/src/parse/schema/classes/jsonSchemaData.js index a9c2d1d..eeb3c42 100644 --- a/src/parse/schema/classes/jsonSchemaData.js +++ b/src/parse/schema/classes/jsonSchemaData.js @@ -1,7 +1,7 @@ module.exports = { - className: "jsonSchemaData", + className: 'jsonSchemaData', fields: { - schemaURL: {type: "String"}, - data: {type: "Object"} - } + schemaURL: { type: 'String' }, + data: { type: 'Object' }, + }, }; diff --git a/src/parse/schema/sanitizeClass.js b/src/parse/schema/sanitizeClass.js index ec473b7..5a15a88 100644 --- a/src/parse/schema/sanitizeClass.js +++ b/src/parse/schema/sanitizeClass.js @@ -1,4 +1,4 @@ -module.exports = schemaClass => { +module.exports = (schemaClass) => { const newSchemaClass = schemaClass; // even if it's set on the schema classes we remove it to be sure the great type an properties is setup diff --git a/src/parse/schema/sync.js b/src/parse/schema/sync.js index 8db006a..a564460 100644 --- a/src/parse/schema/sync.js +++ b/src/parse/schema/sync.js @@ -1,5 +1,5 @@ const Config = require('parse-server/lib/Config'); -const logger = require('./../../logger'); +const logger = require('../../logger'); const getClasses = require('./getClasses'); const sanitizeClass = require('./sanitizeClass'); const initClasses = require('./_initClasses'); @@ -36,7 +36,7 @@ async function applySchemaSync(schema, schemaClass) { } } -module.exports = async appId => { +module.exports = async (appId) => { const schemaClasses = await getClasses(); const schema = await Config.get(appId).database.loadSchema(); diff --git a/webpack.conf.js b/webpack.config.js similarity index 86% rename from webpack.conf.js rename to webpack.config.js index a1ba311..94e753b 100644 --- a/webpack.conf.js +++ b/webpack.config.js @@ -14,7 +14,7 @@ const indexTemplate = getPath('src/front/public/index.html'); const EXTRACT_CSS = process.env.NODE_ENV === 'production'; const APPLY_OPTIMIZATIONS = process.env.NODE_ENV === 'production'; -const scssLoaders = cssOptions => [ +const scssLoaders = (cssOptions) => [ EXTRACT_CSS ? MiniCssExtractPlugin.loader : 'style-loader', { loader: 'css-loader', @@ -27,11 +27,13 @@ module.exports = () => { const env = dotenv.config().parsed; // reduce it to a nice object, the same as before - const envKeys = env ? Object.keys(env).reduce((prev, next) => { - // eslint-disable-next-line no-param-reassign - prev[`process.env.${next}`] = JSON.stringify(env[next]); - return prev; - }, {}) : {}; + const envKeys = env + ? Object.keys(env).reduce((prev, next) => { + // eslint-disable-next-line no-param-reassign + prev[`process.env.${next}`] = JSON.stringify(env[next]); + return prev; + }, {}) + : {}; return { mode: process.env.NODE_ENV || 'development', @@ -45,7 +47,7 @@ module.exports = () => { devServer: { inline: true, port: process.env.FRONT_PORT, - historyApiFallback: true + historyApiFallback: true, }, module: { rules: [ @@ -106,11 +108,11 @@ module.exports = () => { }, optimization: APPLY_OPTIMIZATIONS ? { - runtimeChunk: 'single', - splitChunks: { - chunks: 'all', - }, - } + runtimeChunk: 'single', + splitChunks: { + chunks: 'all', + }, + } : {}, - } + }; };