Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added firebase as storage #1

Open
wants to merge 3 commits into
base: csb-0z3f1
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 6 additions & 11 deletions api/adminCoupons.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { jsonResponse } from "../util/jsonResponse";
import fs from "fs";
import path from "path";
import url from "url";
import hash from "js-sha1";
import filesystem from "./service/filesystem";

export default function(req, res, next) {
export default async function(req, res, next) {
let token;

try {
Expand All @@ -13,17 +13,12 @@ export default function(req, res, next) {
return jsonResponse(res, {}, 400);
}

if (token !== require("js-sha1")("boomyeah123456qwertz")) {
if (token !== hash(process.env.secret)) {
jsonResponse(res, { error: "Wrong token" }, 401);
}

const data = fs.readFileSync(
path.resolve(__dirname, "../data/coupons.json"),
"utf8"
);
const coupons = await filesystem.getAll("coupon");
jsonResponse(res, {
coupons: JSON.parse(data).map(coupon => {
return coupon;
})
coupons
});
}
30 changes: 6 additions & 24 deletions api/adminFile.js
Original file line number Diff line number Diff line change
@@ -1,29 +1,15 @@
import { jsonResponse } from "../util/jsonResponse";
import path from "path";
import fs from "fs";
import hash from "js-sha1";
import filesystem from "./service/filesystem";

export default function(req, res, next) {
let coupons;
export default async function(req, res, next) {
let { token, file, couponId } = req.body;

if (token !== require("js-sha1")("boomyeah123456qwertz")) {
if (token !== hash(process.env.secret)) {
jsonResponse(res, { error: "Wrong token" }, 401);
}

try {
coupons = JSON.parse(
fs.readFileSync(path.resolve(__dirname, "../data/coupons.json"), "utf8")
);
} catch (e) {
return jsonResponse(
res,
{
error:
"Ein interner Fehler ist aufgetreten. Coupons sind nicht richtig konfiguriert."
},
500
);
}
const coupons = await filesystem.getAll("coupon");

const couponIndex = coupons.findIndex(c => c.id === couponId);
if (couponIndex === -1) {
Expand All @@ -36,11 +22,7 @@ export default function(req, res, next) {

coupons[couponIndex].image = file;

fs.writeFileSync(
path.resolve(__dirname, "../data/coupons.json"),
JSON.stringify(coupons),
"utf8"
);
filesystem.save("coupon", coupons[couponIndex].id, coupons[couponIndex]);

jsonResponse(res, {
coupons
Expand Down
11 changes: 0 additions & 11 deletions api/chart.js

This file was deleted.

38 changes: 5 additions & 33 deletions api/coupons.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,11 @@
import { jsonResponse } from "../util/jsonResponse";
import fs from "fs";
import path from "path";
import filesystem from "./service/filesystem";

export default function(req, res, next) {
if (!fs.existsSync(path.resolve(__dirname, "../data/"))) {
console.log("Data does not exists!");
fs.mkdirSync(path.resolve(__dirname, "../data/"));
} else {
console.log("Data does exist.");
}

if (!fs.existsSync(path.resolve(__dirname, "../data/coupons.json"))) {
console.log("Coupons data does not exists!");
fs.writeFileSync(
path.resolve(__dirname, "../data/coupons.json"),
"[]",
"utf8"
);
}

if (!fs.existsSync(path.resolve(__dirname, "../data/chart.json"))) {
console.log("Cart data does not exists!");
fs.writeFileSync(
path.resolve(__dirname, "../data/chart.json"),
"{}",
"utf8"
);
}

const data = fs.readFileSync(
path.resolve(__dirname, "../data/coupons.json"),
"utf8"
);
export default async function(req, res, next) {
const coupons = await filesystem.getAll("coupon");
//console.log("[coupons] from storage: ", coupons);
jsonResponse(res, {
coupons: JSON.parse(data)
coupons: coupons
.filter(c => c.active)
.map(coupon => {
if (coupon.balance === 0 || coupon.usageCount >= coupon.balance) {
Expand Down
5 changes: 3 additions & 2 deletions api/login.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { jsonResponse } from "../util/jsonResponse";
import url from "url";
import hash from "js-sha1";

export default function(req, res, next) {
let password;
Expand All @@ -11,11 +12,11 @@ export default function(req, res, next) {
return jsonResponse(res, {}, 400);
}

if (password !== "yeahyeah") {
if (password !== process.env.ADMIN_PASSWORD) {
return jsonResponse(res, { error: "Wrong credentials." }, 401);
}

jsonResponse(res, {
token: require("js-sha1")("boomyeah123456qwertz")
token: hash(process.env.secret)
});
}
15 changes: 6 additions & 9 deletions api/rawCoupon.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import { jsonResponse } from "../util/jsonResponse";
import fs from "fs";
import path from "path";
import url from "url";
import hash from "js-sha1";
import filesystem from "./service/filesystem";

export default function(req, res, next) {
export default async function(req, res, next) {
let couponId, token;

try {
Expand All @@ -13,16 +13,13 @@ export default function(req, res, next) {
} catch (e) {
return jsonResponse(res, {}, 400);
}
if (token !== require("js-sha1")("boomyeah123456qwertz")) {
if (token !== hash(process.env.secret)) {
jsonResponse(res, { error: "Wrong token" }, 401);
}
const data = fs.readFileSync(
path.resolve(__dirname, "../data/coupons.json"),
"utf8"
);
const coupons = await filesystem.getAll("coupon");
jsonResponse(res, {
rawCoupon: JSON.stringify(
JSON.parse(data)
coupons
.map(coupon => {
if (coupon.balance === 0 || coupon.usageCount >= coupon.balance) {
coupon.active = false;
Expand Down
36 changes: 11 additions & 25 deletions api/saveCoupon.js
Original file line number Diff line number Diff line change
@@ -1,39 +1,30 @@
import { jsonResponse } from "../util/jsonResponse";
import path from "path";
import fs from "fs";
import couponSchema from "../schema/couponSchema";
import tv4 from "tv4";
import filesystem from "./service/filesystem";
import hash from "js-sha1";

export default function(req, res, next) {
let coupons;
export default async function(req, res, next) {
let { token, coupon } = req.body;

if (!tv4.validate(coupon, couponSchema)) {
return jsonResponse(res, { error: "Wrong format", detail: tv4.error }, 400);
}

if (token !== require("js-sha1")("boomyeah123456qwertz")) {
if (token !== hash(process.env.secret)) {
return jsonResponse(res, { error: "Wrong token" }, 401);
}

try {
coupons = JSON.parse(
fs.readFileSync(path.resolve(__dirname, "../data/coupons.json"), "utf8")
);
} catch (e) {
return jsonResponse(
res,
{
error:
"Ein interner Fehler ist aufgetreten. Coupons sind nicht richtig konfiguriert."
},
500
);
}
const coupons = await filesystem.getAll("coupon");

console.log("[saveCoupon] coupons: ", coupons);

const couponIndex = coupons.findIndex(c => c.id === coupon.id);

console.log("[saveCoupon] couponIndex: ", couponIndex);
if (couponIndex === -1) {
coupons.push(coupon);
filesystem.save("coupon", coupon.id, coupon);
} else {
try {
for (const key in coupon) {
Expand All @@ -44,17 +35,12 @@ export default function(req, res, next) {
coupons[couponIndex][key] = coupon[key];
}
}
filesystem.save("coupon", coupons[couponIndex].id, coupons[couponIndex]);
} catch (e) {
console.error("Error on update: ", e);
}
}

fs.writeFileSync(
path.resolve(__dirname, "../data/coupons.json"),
JSON.stringify(coupons),
"utf8"
);

jsonResponse(res, {
coupons
});
Expand Down
47 changes: 47 additions & 0 deletions api/service/filesystem.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
import admin from "firebase-admin";
const serviceAccount = JSON.parse(process.env.FIREBASE);

let db;

function _init() {
if (db) return;

if (admin.apps.length === 0) {
admin.initializeApp({
credential: admin.credential.cert(serviceAccount)
});
}

db = admin.firestore();
}

async function save(type, key, data) {
_init();
await db
.collection(type)
.doc(key)
.set(data);
console.log("[filesystem] Stored: ", type, key);
}

async function getAll(type) {
_init();
try {
const querySnapshot = await db.collection(type).get();
return querySnapshot.docs.map(doc => doc.data());
/*const docs = [];
querySnapshot.forEach(doc => {
console.log("[filesystem] snapshot value: ", doc);
docs.push(doc);
});
return docs;*/
} catch (e) {
console.error("[filesystem] Error on getAll: ", e);
return [];
}
}

export default {
getAll,
save
};
63 changes: 6 additions & 57 deletions api/submitCoupon.js
Original file line number Diff line number Diff line change
@@ -1,23 +1,9 @@
import { jsonResponse } from "../util/jsonResponse";
import fs from "fs";
import path from "path";
import url from "url";
import filesystem from "./service/filesystem";

function formatDate(date, format) {
return format
.replace("YYYY", date.getFullYear())
.replace(
"MM",
(date.getMonth() + 1 < 10 ? "0" : "") + (date.getMonth() + 1)
)
.replace("DD", (date.getDate() < 10 ? "0" : "") + date.getDate())
.replace("hh", (date.getHours() < 10 ? "0" : "") + date.getHours())
.replace("mm", (date.getMinutes() < 10 ? "0" : "") + date.getMinutes())
.replace("ss", (date.getSeconds() < 10 ? "0" : "") + date.getSeconds());
}

export default function(req, res, next) {
let couponId, authCode, coupons, chartData;
export default async function(req, res, next) {
let couponId, authCode;

try {
let { coupon_id, code } = url.parse(req.url, true).query;
Expand All @@ -27,41 +13,7 @@ export default function(req, res, next) {
return jsonResponse(res, {}, 400);
}

try {
coupons = JSON.parse(
fs.readFileSync(path.resolve(__dirname, "../data/coupons.json"), "utf8")
);
} catch (e) {
return jsonResponse(
res,
{
error:
"Ein interner Fehler ist aufgetreten. Coupons sind nicht richtig konfiguriert."
},
500
);
}

try {
chartData = JSON.parse(
fs.readFileSync(path.resolve(__dirname, "../data/chart.json"), "utf8")
);
if (!chartData[couponId]) {
chartData[couponId] = {};
}
const timestamp = formatDate(new Date(), "YYYY-MM-DD-hh");
if (!chartData[couponId][timestamp]) {
chartData[couponId][timestamp] = 0;
}
chartData[couponId][timestamp]++;
fs.writeFileSync(
path.resolve(__dirname, "../data/chart.json"),
JSON.stringify(chartData),
"utf8"
);
} catch (e) {
console.error("Error on writing chart data: ", e);
}
const coupons = await filesystem.getAll("coupon");

const couponIndex = coupons.findIndex(c => c.id === couponId);
if (couponIndex === -1) {
Expand Down Expand Up @@ -89,11 +41,8 @@ export default function(req, res, next) {
);
}
coupons[couponIndex].usageCount++;
fs.writeFileSync(
path.resolve(__dirname, "../data/coupons.json"),
JSON.stringify(coupons),
"utf8"
);

filesystem.save("coupon", coupons[couponIndex].id, coupons[couponIndex]);

jsonResponse(res, {}, 200);
}
Loading