Skip to content

Commit

Permalink
fix account test case to delete ledger after all
Browse files Browse the repository at this point in the history
  • Loading branch information
tim-hub committed Jul 11, 2020
1 parent 9458d16 commit 18d0ff9
Show file tree
Hide file tree
Showing 9 changed files with 272 additions and 11 deletions.
10 changes: 5 additions & 5 deletions jest.setup.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,16 +10,16 @@ const user2Data = {
};

beforeAll(async () => {
logger.debug('before all');
logger.info('before all');
await prepareConnection();
logger.debug('get test connection done');
logger.info('get test connection done');

const UserRepo = User.getRepo();
const user = (await UserRepo.create(user2Data));
await UserRepo.save(user);


logger.debug(user2Data.userName, 'test user and ledger created');
logger.info(user2Data.userName, 'test user and ledger created');
});

afterAll(async () => {
Expand All @@ -28,9 +28,9 @@ afterAll(async () => {
DELETE FROM USER WHERE email = '${user2Data.email}';
`
);
logger.debug('test data deleted');
logger.info('test data deleted');

const defaultConnection = getConnection();
await defaultConnection.close();
logger.debug('close connections done');
logger.info('close connections done');
});
2 changes: 1 addition & 1 deletion ormconfig-json.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
"type": "sqlite",
"database": "database.sqlite",
"synchronize": false,
"logging": ["error", "query", "schema"],
"logging": false,
"entities": [
"src/entity/**/*.ts"
],
Expand Down
2 changes: 1 addition & 1 deletion ormconfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ if (process.env.JEST_TESTING === 'true') {
type: "sqlite",
database: "test.sqlite",
synchronize: false,
logging: ['error', 'query', 'schema'],
logging: false,
});
}

Expand Down
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
"start:heroku": "cross-env BYPATH_ACCESS_TOKEN=false npm run postinstall && node dist/server.js",
"seed": "ts-node src/db/seeding/index.ts",
"postinstall": "npx tsc",
"test": "cross-env JEST_TESTING=true jest --testTimeout=10000 --runInBand",
"test": "cross-env JEST_TESTING=true LOG_LEVEL=debug jest --testTimeout=10000 --runInBand",
"test:db:migrate": "cross-env JEST_TESTING=true ts-node ./node_modules/typeorm/cli.js migration:run",
"db:migration": " ts-node ./node_modules/typeorm/cli.js migration:generate",
"db:gen-migration": "npm run db:migration -- -n auto",
Expand Down
1 change: 0 additions & 1 deletion src/logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,6 @@ import * as pino from 'pino';

const logger = pino(
{
name: 'mm-log',
level: process.env?.LOG_LEVEL ? process.env?.LOG_LEVEL : 'info',
}
);
Expand Down
7 changes: 5 additions & 2 deletions src/middleware/getLedgerMiddleware.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { Ledger } from '../entity/Ledger';
import logger from '../logger';

export const getLedger = async (req, res, next) => {
const ledgerID = req?.params?.ledgerID;
Expand All @@ -7,14 +8,16 @@ export const getLedger = async (req, res, next) => {
}
try {
const ledger = await Ledger.getRepo().findOne(ledgerID);
console.log(ledger, req.user.id);
logger.debug('middleware ledger req');
logger.debug(ledger);
logger.debug( req.user.id)
if (!ledger || ledger.userId !== req.user.id) {
res.status(403).send('forbidden for this ledger');
}
req.ledgerID = ledgerID;
next();
} catch (e) {
console.error(e);
logger.error(e);
res.status(400).send('ledger id is required');
}
};
148 changes: 148 additions & 0 deletions src/services/account/accountRouter.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import theRouter from './accountRouter';
import * as supertest from 'supertest';
import * as express from "express";
import { getOrmManager } from '../../db/ormManager';
import { User } from '../../entity/User';
import { signAccessToken } from '../auth/provider';
import { Ledger } from '../../entity/Ledger';

const app = express();
app.use('/', theRouter);

const entityData = {
name: 'test-account',
description: 'haha optional',
amount: 100,
ledgerID: null,
};


const ledger2Data = {
name: 'ledger2haha2',
userId: null,
};

describe("routes", () => {
let token;
let user;
let ledger;
let entity;
let updatedEntityData;

beforeAll(async () => {
const UserRepo = User.getRepo();
const users = await UserRepo.find();
user = users[0];
token = signAccessToken(users[0].id, user.email);

const ledgerRepo = Ledger.getRepo();
ledger = await ledgerRepo.create(ledger2Data);
ledger.user=user;
await ledgerRepo.save(ledger);
});

afterAll(async () => {
await getOrmManager().query(
`
DELETE FROM LEDGER where name = '${ledger.name}';
DELETE FROM ACCOUNT;
`
);
});

it('get all before create, should be empty', async () => {
const resp = await supertest(app).get('/'+ledger.id)
.set({'Authorization': token}
);
expect(resp.status).toEqual(204);
expect(!resp.body?.length);
});

// it('create one', async () => {
// const resp = await supertest(app).post('/'+ledger.id)
// .send(entityData)
// .set({'Authorization': token}
// );
// expect(resp.status).toEqual(200);
// expect(resp.body.name).toEqual(entityData.name);
// expect(resp.body.ledgerId).toEqual(+ledger.id);
// entity = resp.body;
// });
//
// it('get one', async () => {
// const resp = await supertest(app).get(`/${ledger.id}/${entity.id}`)
// .set({'Authorization': token}
// );
// expect(resp.status).toEqual(200);
// expect(resp.body.name).toEqual(entityData.name);
// });
//
// it('get all should be one', async () => {
// const resp = await supertest(app).get(`/${ledger.id}`)
// .set({'Authorization': token}
// );
// expect(resp.status).toEqual(200);
// expect(resp.body.length).toEqual(1);
// });
//
// it('shout not get not existed one', async () => {
// const resp = await supertest(app).get(`/${ledger.id}/${entity.id+1}`)
// .set({'Authorization': token}
// );
// expect(resp.status).toEqual(204);
// });
//
// it('update one', async () => {
// const tmpEntity = {...entityData};
// updatedEntityData = {
// ...tmpEntity,
// name: 'test-entity-1',
// };
// const resp = await supertest(app).put(`/${ledger.id}/${entity.id}`)
// .send(updatedEntityData)
// .set({'Authorization': token}
// );
// expect(resp.status).toEqual(200);
// });
//
// it('get updated one', async () => {
// const resp = await supertest(app).get(`/${ledger.id}/${entity.id}`)
// .set({'Authorization': token}
// );
// expect(resp.status).toEqual(200);
// expect(resp.body.name).toEqual(updatedEntityData.name);
// });
//
// it('should not update not existed one', async () => {
// updatedEntityData = {
// ...entity,
// name: 'test-entity-1',
// };
// const resp = await supertest(app).put(`/${ledger.id}/${entity.id+1}`)
// .send(updatedEntityData)
// .set({'Authorization': token}
// );
// expect(resp.status).toEqual(400);
// });
//
// it('delete the one', async () => {
// const resp = await supertest(app).delete(`/${ledger.id}/${entity.id}`)
// .set({'Authorization': token}
// );
// expect(resp.status).toEqual(200);
// });
//
// it('should not delete un-exited one', async () => {
// const resp = await supertest(app).delete(`/${ledger.id}/${entity.id+1}`)
// .set({'Authorization': token}
// );
// expect(resp.status).toEqual(400);
// });
//
// it('should not get after delete', async () => {
// const resp = await supertest(app).get(`/${ledger.id}/${entity.id}`)
// .set({'Authorization': token}
// );
// expect(resp.status).toEqual(204);
// });
});
20 changes: 20 additions & 0 deletions src/services/account/accountRouter.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
import * as express from 'express';
import * as services from './accountService';
import { handleBodyRequestParsing } from '../../middleware/common';
import { authenticateJWT } from '../../middleware/jwtAuthMiddleWare';
import { getLedger } from '../../middleware/getLedgerMiddleware';

const router = express.Router();

handleBodyRequestParsing(router);
router.use(authenticateJWT);


router.post('/:ledgerID', getLedger, services.createOne);
router.get('/:ledgerID', getLedger, services.getAll);
router.put('/:ledgerID/:entityID', getLedger, services.updateOne);
router.get('/:ledgerID/:entityID', getLedger, services.getOne);
router.delete('/:ledgerID/:entityID', getLedger, services.deleteOne);


export default router;
91 changes: 91 additions & 0 deletions src/services/account/accountService.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,91 @@
import { Response } from 'express';
import { Account as Entity } from '../../entity/Account';


const getFindOption = (ledgerId) => (
{
where: {
ledgerId: ledgerId
}
}
);

export const getAll = async (req: any, res: Response) => {
const entityRepo = Entity.getRepo();
try {
const items = await entityRepo.find(
getFindOption(req.ledgerID)
);
if (items?.length) {
res.status(200).send(items);
} else {
res.status(204).send([]);
}
} catch (e) {
console.error(e);
res.status(500).end();
}
};


export const getOne = async (req: any, res: Response) => {
const entityRepo = Entity.getRepo();
const ledgerID = req.ledgerID;
try {
const item = await entityRepo.findOne(ledgerID, getFindOption(ledgerID));
if (item) {
res.status(200).send(item);
} else {
res.status(204).send({});
}
} catch (e) {
console.error(e);
res.status(500).end();
}
};

export const createOne = async (req, res: Response) => {
const entityRepo = Entity.getRepo();
try {
const item = await entityRepo.create(req.body) as unknown as Entity;
item.ledgerId = req.ledgerID;
await entityRepo.save(item);
res.status(200).send(item);
} catch (e) {
console.error(e);
res.status(500).end();
}
};

export const updateOne = async (req, res: Response) => {
const ledgerID = req.params?.ledgerID;
const entityRepo = Entity.getRepo();
try {
const item = await entityRepo.findOne(ledgerID, getFindOption(ledgerID));
if (item) {
const r = await entityRepo.update(item.id, req.body);
res.status(200).send(r);
}
res.status(400).end();
} catch (e) {
console.error(e);
res.status(500).end();
}
};

export const deleteOne = async (req, res: Response) => {
const ledgerID = req.params?.ledgerID;
const entityRepo = Entity.getRepo();
try {
const item = await entityRepo.findOne(ledgerID, getFindOption(req.ledgerID));
if (item) {
await entityRepo.softDelete(item.id);
res.status(200).json({});
} else {
res.status(400).end();
}
} catch (e) {
console.error(e);
res.status(500).end();
}
};

0 comments on commit 18d0ff9

Please sign in to comment.