Skip to content

Commit

Permalink
refactor(jsbattle-server): remove pagination from API where not neces…
Browse files Browse the repository at this point in the history
…sary
  • Loading branch information
jamro committed Apr 16, 2020
1 parent 9da9c71 commit fa1c5ac
Show file tree
Hide file tree
Showing 14 changed files with 59 additions and 62 deletions.
28 changes: 18 additions & 10 deletions packages/jsbattle-mockserver/app/MockServer.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const querystring = require('querystring')
const jsonServer = require('json-server')
const bodyParser = require('body-parser')
const _ = require('lodash');
const config = require(path.resolve(__dirname, 'config.json'));

class MockServer {

Expand Down Expand Up @@ -44,6 +45,7 @@ class MockServer {
let authorized = !!(options.authorized);

router.render = (req, res) => {
// modify default response here
if(req.url == '/profile' && !authorized) {
return res.jsonp({});
}
Expand All @@ -53,16 +55,22 @@ class MockServer {
if(!Array.isArray(res.locals.data)) {
return res.jsonp(res.locals.data);
}
let params = querystring.parse(req.url.split('?').pop());
let page = params._page || 1;
let pageSize = params._limit || 10;
res.jsonp({
rows: res.locals.data,
total: 500,
page: page,
pageSize: pageSize,
totalPages: Math.ceil(500/pageSize)
})
for(let pattern of config.pagination) {
pattern = new RegExp(pattern);
if(pattern.test(req.url)) {
let params = querystring.parse(req.url.split('?').pop());
let page = params._page || 1;
let pageSize = params._limit || 10;
return res.jsonp({
rows: res.locals.data,
total: 500,
page: page,
pageSize: pageSize,
totalPages: Math.ceil(500/pageSize)
})
}
}
return res.jsonp(res.locals.data);
}

server.use('/', express.static(publicDir));
Expand Down
6 changes: 6 additions & 0 deletions packages/jsbattle-mockserver/app/config.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
{
"pagination": [
"admin,users",
"admin,battles"
]
}
6 changes: 3 additions & 3 deletions packages/jsbattle-react/public/tanks/circler.tank.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
importScripts('lib/tank.js');

tank.init(function(settings, info) {
settings.SKIN = "forest"
settings.SKIN = "forest";

wander_turn_counter = 0;
circle_dir = 1.0;
Expand All @@ -21,7 +21,7 @@ function controlGun(state, control) {
// Predict where the enemy will be to adjust the gun angle.
let enemy = state.radar.enemy;
let bullet_speed = 4;
let distance = Math.distance(state.x, state.y, enemy.x, enemy.y)
let distance = Math.distance(state.x, state.y, enemy.x, enemy.y);
let bullet_time = distance / bullet_speed;
let target = {x: enemy.x + bullet_time * enemy.speed * Math.cos(Math.deg2rad(enemy.angle)),
y: enemy.y + bullet_time * enemy.speed * Math.sin(Math.deg2rad(enemy.angle))};
Expand Down Expand Up @@ -73,7 +73,7 @@ function circleEnemy(state, control) {
let enemy = state.radar.enemy;

// Get the unit vector from us to the enemy.
let r = Math.distance(state.x, state.y, enemy.x, enemy.y)
let r = Math.distance(state.x, state.y, enemy.x, enemy.y);
let u = {x: (enemy.x - state.x) / r,
y: (enemy.y - state.y) / r};

Expand Down
7 changes: 4 additions & 3 deletions packages/jsbattle-server/app/services/Challenge.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,20 +62,21 @@ class ChallengeService extends Service {
});
}

listUserChallanges(ctx) {
async listUserChallanges(ctx) {
const userId = ctx.meta.user ? ctx.meta.user.id : null;
if(!userId) {
throw new ValidationError('Not Authorized!', 401);
}
return ctx.call('challenges.list', {
let result = await ctx.call('challenges.list', {
query: {
userId: userId
},
fields: [
"challengeId",
"completed"
]
})
});
return result.rows;
}

async getUserChallange(ctx) {
Expand Down
7 changes: 4 additions & 3 deletions packages/jsbattle-server/app/services/ScriptStore.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -75,13 +75,13 @@ class ScriptStoreService extends Service {
});
}

listUserScripts(ctx) {
async listUserScripts(ctx) {
const userId = ctx.meta.user ? ctx.meta.user.id : null;
if(!userId) {
throw new ValidationError('Not Authorized!', 401);
}

return ctx.call('scriptStore.list', {
let result = await ctx.call('scriptStore.list', {
query: {
ownerId: userId,
namespace: 'user'
Expand All @@ -94,7 +94,8 @@ class ScriptStoreService extends Service {
"createdAt",
"modifiedAt"
]
})
});
return result.rows;
}

async createUserScript(ctx) {
Expand Down
5 changes: 1 addition & 4 deletions packages/jsbattle-server/test/unit/Challenge.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -69,10 +69,7 @@ describe("Test 'Challenge' service", () => {
id: '92864'
}
let result = await broker.call('challenges.listUserChallanges', {}, {meta: {user: createTestToken(user)}});

expect(result).toHaveProperty('total', 0);
expect(result).toHaveProperty('rows');
expect(result.rows).toHaveProperty('length', 0);
expect(result).toHaveLength(0);
});

it('should create new challenge if does not exist on get operation', async () => {
Expand Down
11 changes: 2 additions & 9 deletions packages/jsbattle-server/test/unit/ScriptStore.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -88,12 +88,7 @@ describe("Test 'ScriptStore' service", () => {
await broker.call('scriptStore.createUserScript', {}, {meta: {user: createTestToken(user)}});
await broker.call('scriptStore.createUserScript', {}, {meta: {user: createTestToken(user)}});
let result = await broker.call('scriptStore.listUserScripts', {}, {meta: {user: createTestToken(user)}});
expect(result).toHaveProperty('total', 3);
expect(result).toHaveProperty('page', 1);
expect(result).toHaveProperty('pageSize', 10);
expect(result).toHaveProperty('totalPages', 1);
expect(result).toHaveProperty('rows');
expect(result.rows).toHaveProperty('length', 3);
expect(result).toHaveLength(3);
});

it('should update user scripts', async () => {
Expand Down Expand Up @@ -148,9 +143,7 @@ describe("Test 'ScriptStore' service", () => {
let result = await broker.call('scriptStore.createUserScript', {}, {meta: {user: createTestToken(user)}});
await broker.call('scriptStore.deleteUserScript', {id: result.id}, {meta: {user: createTestToken(user)}});
result = await broker.call('scriptStore.listUserScripts', {}, {meta: {user: createTestToken(user)}});
expect(result).toHaveProperty('total', 1);
expect(result).toHaveProperty('rows');
expect(result.rows).toHaveProperty('length', 1);
expect(result).toHaveLength(1);
});

});
Expand Down
2 changes: 1 addition & 1 deletion packages/jsbattle-webpage/src/actions/challengeAction.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ async function fetchChallengeList(useRemoteService) {
throw new new Error(`Error ${remoteResponse.status}: ${remoteResponse || remoteResponse.statusText}`)();
}
let json = await remoteResponse.json();
completeChallengeList = json.rows
completeChallengeList = json
.filter((row) => row.completed)
.map((row) => row.challengeId);
} else {
Expand Down
2 changes: 1 addition & 1 deletion packages/jsbattle-webpage/src/containers/SandboxScreen.js
Original file line number Diff line number Diff line change
Expand Up @@ -296,7 +296,7 @@ const mapStateToProps = (state) => ({
isRenameLoading: state.loading.AI_SCRIPT_RENAME,
simQuality: state.settings.simQuality,
simSpeed: state.settings.simSpeed,
userTankList: state.aiRepo.tankList.rows,
userTankList: state.aiRepo.tankList,
bundledTankList: state.sandbox.tankList,
opponent: state.sandbox.opponent,
mode: state.sandbox.mode,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ ScriptListScreen.propTypes = {
};

const mapStateToProps = (state) => ({
tankList: state.aiRepo.tankList.rows,
tankList: state.aiRepo.tankList,
isLoading: state.loading.SANDBOX_AI_SCRIPT_LIST,
isCreating: state.loading.CREATE_AI_SCRIPT,
isDeleting: state.loading.DELETE_AI_SCRIPT,
Expand Down
4 changes: 1 addition & 3 deletions packages/jsbattle-webpage/src/reducers/aiRepoReducer.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,7 @@ import {
} from '../actions/actionTypes.js';

const initState = {
tankList: {
rows: []
}
tankList: []
};


Expand Down
23 changes: 10 additions & 13 deletions packages/jsbattle-webpage/src/reducers/test/aiRepoReducer.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,20 @@ import {

test('has init state', () => {
const outcomeState = aiRepoReducer();
expect(outcomeState).toHaveProperty('tankList')
expect(outcomeState.tankList).toHaveProperty('rows')
expect(outcomeState).toHaveProperty('tankList');
});

test('update tank list', () => {
const outcomeState = aiRepoReducer({}, {
type: SANDBOX_AI_SCRIPT_LIST_SUCCESS,
payload: {
rows: [
{ id: 'op1', scriptName: 'alpha753' },
{ id: 'op2', scriptName: 'beta78732' }
]
}
payload: [
{ id: 'op1', scriptName: 'alpha753' },
{ id: 'op2', scriptName: 'beta78732' }
]
});
expect(outcomeState.tankList.rows).toHaveLength(2);
expect(outcomeState.tankList.rows[0]).toHaveProperty('id', 'op1');
expect(outcomeState.tankList.rows[1]).toHaveProperty('id', 'op2');
expect(outcomeState.tankList.rows[0]).toHaveProperty('scriptName', 'alpha753');
expect(outcomeState.tankList.rows[1]).toHaveProperty('scriptName', 'beta78732');
expect(outcomeState.tankList).toHaveLength(2);
expect(outcomeState.tankList[0]).toHaveProperty('id', 'op1');
expect(outcomeState.tankList[1]).toHaveProperty('id', 'op2');
expect(outcomeState.tankList[0]).toHaveProperty('scriptName', 'alpha753');
expect(outcomeState.tankList[1]).toHaveProperty('scriptName', 'beta78732');
});
3 changes: 0 additions & 3 deletions packages/jsbattle-webpage/src/services/aiRepoService.js
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,6 @@ export const getScriptNameList = async () => {
id: 'local_' + name,
scriptName: name
}));
result = {
rows: result
};
return result;
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -145,14 +145,13 @@ test('list scripts is empty by default', async () => {
}
}));
let result = await getScriptNameList();
expect(result).toHaveProperty('rows');
expect(result.rows).toHaveLength(2);
expect(result.rows[0]).toHaveProperty('id', 'local_duck873');
expect(result.rows[0]).toHaveProperty('scriptName', 'duck873');
expect(result.rows[0]).not.toHaveProperty('code');
expect(result.rows[1]).toHaveProperty('id', 'local_cat762');
expect(result.rows[1]).toHaveProperty('scriptName', 'cat762');
expect(result.rows[1]).not.toHaveProperty('code');
expect(result).toHaveLength(2);
expect(result[0]).toHaveProperty('id', 'local_duck873');
expect(result[0]).toHaveProperty('scriptName', 'duck873');
expect(result[0]).not.toHaveProperty('code');
expect(result[1]).toHaveProperty('id', 'local_cat762');
expect(result[1]).toHaveProperty('scriptName', 'cat762');
expect(result[1]).not.toHaveProperty('code');
});

test('update script', async () => {
Expand Down

0 comments on commit fa1c5ac

Please sign in to comment.