This commit is contained in:
Ace Nassri 2018-08-20 18:23:04 -07:00
parent 70e4d4aec3
commit 18d0810580
5 changed files with 48 additions and 41 deletions

View file

@ -2,7 +2,11 @@
"name": "grpc-currency-service",
"version": "0.1.0",
"description": "A gRPC currency conversion microservice",
"repository": "TODO",
"repository": "https://github.com/GoogleCloudPlatform/microservices-demo",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"lint": "semistandard *.js"
},
"license": "Apache-2.0",
"dependencies": {
"@google-cloud/debug-agent": "^2.6.0",
@ -15,5 +19,8 @@
"left-pad": "^1.3.0",
"request": "^2.87.0",
"xml2js": "^0.4.19"
},
"devDependencies": {
"semistandard": "^12.0.1"
}
}

View file

@ -16,26 +16,26 @@ const cardValidator = require('simple-card-validator');
const uuid = require('uuid/v4');
class CreditCardError extends Error {
constructor(message) {
constructor (message) {
super(message);
this.code = 400; // Invalid argument error
}
}
class InvalidCreditCard extends CreditCardError {
constructor(cardType) {
constructor (cardType) {
super(`Credit card info is invalid`);
}
}
class UnacceptedCreditCard extends CreditCardError {
constructor(cardType) {
constructor (cardType) {
super(`Sorry, we cannot process ${cardType} credit cards. Only VISA or MasterCard is accepted.`);
}
}
class ExpiredCreditCard extends CreditCardError {
constructor(number, month, year) {
constructor (number, month, year) {
super(`Your credit card (ending ${number.substr(-4)}) expired on ${month}/${year}`);
}
}
@ -46,34 +46,29 @@ class ExpiredCreditCard extends CreditCardError {
* @param {*} request
* @return transaction_id - a random uuid v4.
*/
module.exports = function charge(request) {
module.exports = function charge (request) {
const { amount, credit_card: creditCard } = request;
const cardNumber = creditCard.credit_card_number;
const cardInfo = cardValidator(cardNumber);
const {
card_type: cardType,
valid,
cvv_length: cvvLength,
valid
} = cardInfo.getCardDetails();
if (!valid)
throw new InvalidCreditCard();
if (!valid) { throw new InvalidCreditCard(); }
// Only VISA and mastercard is accepted, other card types (AMEX, dinersclub) will
// throw UnacceptedCreditCard error.
if (!(cardType === 'visa' || cardType == 'mastercard'))
throw new UnacceptedCreditCard(cardType);
if (!(cardType === 'visa' || cardType === 'mastercard')) { throw new UnacceptedCreditCard(cardType); }
// Also validate expiration is > today.
const currentMonth = new Date().getMonth() + 1;
const currentYear = new Date().getFullYear();
const { credit_card_expiration_year: year, credit_card_expiration_month: month } = creditCard;
if ((currentYear * 12 + currentMonth) > (year * 12 + month))
throw new ExpiredCreditCard(cardNumber.replace('-', ''), month, year);
if ((currentYear * 12 + currentMonth) > (year * 12 + month)) { throw new ExpiredCreditCard(cardNumber.replace('-', ''), month, year); }
console.log(`Transaction processed: ${cardType} ending ${cardNumber.substr(-4)} \
Amount: ${amount.currency_code}${amount.units}.${amount.nanos}`)
return { transaction_id: uuid() }
}
Amount: ${amount.currency_code}${amount.units}.${amount.nanos}`);
return { transaction_id: uuid() };
};

View file

@ -17,25 +17,25 @@
'use strict';
require('@google-cloud/profiler').start({
serviceContext: {
service: 'paymentservice',
version: '1.0.0'
}
});
serviceContext: {
service: 'paymentservice',
version: '1.0.0'
}
});
require('@google-cloud/trace-agent').start();
require('@google-cloud/debug-agent').start({
serviceContext: {
service: 'paymentservice',
version: 'VERSION'
}
})
serviceContext: {
service: 'paymentservice',
version: 'VERSION'
}
});
const path = require('path');
const HipsterShopServer = require('./server');
const PORT = process.env['PORT'];
const PROTO_PATH = __dirname + '/proto/';
const PROTO_PATH = path.join(__dirname, '/proto/');
const server = new HipsterShopServer(PROTO_PATH, PORT);
server.listen();

View file

@ -2,9 +2,11 @@
"name": "paymentservice",
"version": "0.0.1",
"description": "Payment Microservice demo",
"repository": "https://github.com/GoogleCloudPlatform/microservices-demo",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
"test": "echo \"Error: no test specified\" && exit 1",
"lint": "semistandard *.js"
},
"author": "Jonathan Lui",
"license": "ISC",
@ -16,5 +18,8 @@
"grpc": "^1.12.3",
"simple-card-validator": "^1.1.0",
"uuid": "^3.2.1"
},
"devDependencies": {
"semistandard": "^12.0.1"
}
}

View file

@ -19,7 +19,7 @@ const protoLoader = require('@grpc/proto-loader');
const charge = require('./charge');
class HipsterShopServer {
constructor(protoRoot, port = HipsterShopServer.DEFAULT_PORT) {
constructor (protoRoot, port = HipsterShopServer.DEFAULT_PORT) {
this.port = port;
this.packages = {
@ -36,10 +36,10 @@ class HipsterShopServer {
* @param {*} call { ChargeRequest }
* @param {*} callback fn(err, ChargeResponse)
*/
static ChargeServiceHandler(call, callback) {
static ChargeServiceHandler (call, callback) {
try {
console.log(`PaymentService#Charge invoked with request ${JSON.stringify(call.request)}`)
const response = charge(call.request)
console.log(`PaymentService#Charge invoked with request ${JSON.stringify(call.request)}`);
const response = charge(call.request);
callback(null, response);
} catch (err) {
console.warn(err);
@ -47,17 +47,17 @@ class HipsterShopServer {
}
}
static CheckHandler(call, callback) {
static CheckHandler (call, callback) {
callback(null, { status: 'SERVING' });
}
listen() {
listen () {
this.server.bind(`0.0.0.0:${this.port}`, grpc.ServerCredentials.createInsecure());
console.log(`PaymentService grpc server listening on ${this.port}`);
this.server.start();
}
loadProto(path) {
loadProto (path) {
const packageDefinition = protoLoader.loadSync(
path,
{
@ -65,20 +65,20 @@ class HipsterShopServer {
longs: String,
enums: String,
defaults: true,
oneofs: true,
oneofs: true
}
);
return grpc.loadPackageDefinition(packageDefinition);
}
loadAllProtos(protoRoot) {
loadAllProtos (protoRoot) {
const hipsterShopPackage = this.packages.hipsterShop.hipstershop;
const healthPackage = this.packages.health.grpc.health.v1;
this.server.addService(
hipsterShopPackage.PaymentService.service,
{
charge: HipsterShopServer.ChargeServiceHandler.bind(this),
charge: HipsterShopServer.ChargeServiceHandler.bind(this)
}
);