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

refactor: #28

Open
wants to merge 2 commits into
base: main
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
6 changes: 5 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,4 +14,8 @@ writer/out/
tasks/node_modules/
publisher/node_modules/

deployment/
deployment/

node_modules
/.idea
yarn.lock
7 changes: 7 additions & 0 deletions publisher/.eslintignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
.next
.idea
.yarn
.eslintrc.js
build
dist
node_modules
61 changes: 61 additions & 0 deletions publisher/.eslintrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
module.exports = {
env: {
es2021: true,
node: true,
},
parserOptions: {
ecmaVersion: 'latest',
},

extends: ['eslint:recommended'],
overrides: [],

plugins: [],
rules: {
indent: [
// отступы
'off',
'tab',
{
SwitchCase: 1,
VariableDeclarator: 'first',
MemberExpression: 1,
outerIIFEBody: 1,
FunctionDeclaration: { parameters: 'first' },
StaticBlock: { body: 1 },
CallExpression: { arguments: 1 },
ArrayExpression: 1,
ObjectExpression: 1,
ImportDeclaration: 1,
flatTernaryExpressions: true,
},
],
quotes: ['warn', 'single'],
semi: ['warn', 'never'], // OFF
'no-empty-pattern': [0], // разрешаем пустую деструктуризацию "{}"
'no-unused-vars': [0], // не используемые переменные
'no-mixed-spaces-and-tabs': [0], // смешивание табов и пробелов , временно
'max-len': [1, { code: 120, tabWidth: 2, comments: 120 }], // Принудительно установите максимальную длину строки
// 'import/order': [1], // сорировка импортов
'comma-dangle': [1, 'always-multiline'], // последняя запятая в массивах ...
camelcase: [0], // переменные пишутся в стиле camelCase
curly: [1, 'all'], // запретить if в одну строку
'no-console': [1], // без консоли "console.log"
'no-empty': [1], // пустые функции
'no-floating-decimal': [1], // запретить числа без 0 ".3 -.5"
'no-implicit-coercion': [1], // явное приведение типов "Number("1")"
'no-unneeded-ternary': [1], // Запрещайте троичные операторы, когда существуют более простые альтернативы
'no-useless-computed-key': [1], // Запретить ненужные вычисляемые ключи свойств в объектах и классах "{['name']:1}"
'prefer-const': [1], // Требовать const объявления для переменных, которые никогда не переназначаются после объявления
'prefer-template': [1], // Требовать шаблонные литералы вместо конкатенации строк
'space-in-parens': [1, 'never'], // Обеспечить согласованный интервал внутри круглых скобок
'space-before-blocks': [1, 'always'], // Обеспечить согласованный интервал перед блоками
// ! ERROR
'no-implied-eval': [2], // запретить непреднамеренный eval "setTimeout("alert('Hi!');", 100)"
eqeqeq: [2], // только 3ое равенство "true === true"
'no-multi-assign': [2], // запретить множественное присвоение "const foo = bar = 0"
'default-param-last': [2], // дефолтные парметры функции пишутся в конце
// 'max-lines': [2, {max: 120, skipBlankLines: true}], // максимальная длина строк в файле
'no-constant-condition': [0],
},
}
4 changes: 4 additions & 0 deletions publisher/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
node_modules
/.idea
yarn.lock

4 changes: 0 additions & 4 deletions publisher/.prettierrc

This file was deleted.

7 changes: 7 additions & 0 deletions publisher/.prettierrc.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
module.exports = {
tabWidth: 2,
useTabs: false,
trailingComma: 'all',
singleQuote: true,
semi: false,
}
197 changes: 98 additions & 99 deletions publisher/app.js
Original file line number Diff line number Diff line change
@@ -1,70 +1,75 @@
var express = require("express");
var path = require("path");
var cookieParser = require("cookie-parser");
var logger = require("morgan");
var exphbs = require("express-handlebars");
var hbsLayout = require("handlebars-layout");
var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')
var exphbs = require('express-handlebars')
var hbsLayout = require('handlebars-layout')

var cron = require("node-cron");
var cron = require('node-cron')

var indexRouter = require("./routes/index");
var internalRouter = require("./routes/internal");
var { genSitemap } = require("./routes/sitemap");
var indexRouter = require('./routes/index')
var internalRouter = require('./routes/internal')
var { genSitemap } = require('./routes/sitemap')

var { cacheUsers, cacheNotes } = require("./logic/notes");
var { cacheUsers, cacheNotes } = require('./logic/notes')

var app = express();
var minifyHTML = require("express-minify-html");
var app = express()
var minifyHTML = require('express-minify-html')

var hbs = exphbs.create({
extname: ".hbs",
defaultLayout: "base",
layoutsDir: path.join(__dirname, "/views/layouts"),
partialsDir: path.join(__dirname, "/views/partials"),
helpers: require("handlebars-helpers")(), // make sure to call the returned function
});
extname: '.hbs',
defaultLayout: 'base',
layoutsDir: path.join(__dirname, '/views/layouts'),
partialsDir: path.join(__dirname, '/views/partials'),
helpers: require('handlebars-helpers')(), // make sure to call the returned function
})

hbs.handlebars.registerHelper(hbsLayout(hbs.handlebars));
hbs.handlebars.registerHelper(hbsLayout(hbs.handlebars))

// register new function
hbs.handlebars.registerHelper("slicer", (str, s, e = null) => str.slice(s, e));
hbs.handlebars.registerHelper("ifDev", (options) => {
if (process.env.NODE_ENV !== "production") {
return options.fn(this);
} else return options.inverse(this);
});
hbs.handlebars.registerHelper("ifIsNthItem", function (options) {
hbs.handlebars.registerHelper('slicer', (str, s, e = null) => str.slice(s, e))
hbs.handlebars.registerHelper('ifDev', (options) => {
if (process.env.NODE_ENV !== 'production') {
return options.fn(this)
} else {
return options.inverse(this)
}
})
hbs.handlebars.registerHelper('ifIsNthItem', function (options) {
var index = options.data.index + 1,
nth = options.hash.nth,
val = options.hash.val;
val = options.hash.val

if (index % nth === val || 0) return options.fn(this);
else return options.inverse(this);
});
hbs.handlebars.registerHelper("dateddmmyyy", function (str) {
if (index % nth === val || 0) {
return options.fn(this)
} else {
return options.inverse(this)
}
})
hbs.handlebars.registerHelper('dateddmmyyy', function (str) {
const intervals = [
{ label: "year", seconds: 31536000 },
{ label: "month", seconds: 2592000 },
{ label: "day", seconds: 86400 },
{ label: "hour", seconds: 3600 },
{ label: "minute", seconds: 60 },
{ label: "second", seconds: 1 },
];
{ label: 'year', seconds: 31536000 },
{ label: 'month', seconds: 2592000 },
{ label: 'day', seconds: 86400 },
{ label: 'hour', seconds: 3600 },
{ label: 'minute', seconds: 60 },
{ label: 'second', seconds: 1 },
]

function timeSince(date) {
const seconds = Math.floor((Date.now() - date.getTime()) / 1000);
const interval = intervals.find((i) => i.seconds < seconds);
const count = Math.floor(seconds / interval.seconds);
return `${count} ${interval.label}${count !== 1 ? "s" : ""} ago`;
const seconds = Math.floor((Date.now() - date.getTime()) / 1000)
const interval = intervals.find((i) => i.seconds < seconds)
const count = Math.floor(seconds / interval.seconds)
return `${count} ${interval.label}${count !== 1 ? 's' : ''} ago`
}

return timeSince(new Date(str));
});
return timeSince(new Date(str))
})

// Minifier setup
app.use(
minifyHTML({
override: process.env.NODE_ENV === "production",
override: process.env.NODE_ENV === 'production',
exception_url: false,
htmlMinifier: {
removeComments: true,
Expand All @@ -75,31 +80,31 @@ app.use(
minifyJS: true,
minifyCSS: true,
},
})
);
}),
)

if (process.env.NODE_ENV == "production") {
app.set("trust proxy", 1);
if (process.env.NODE_ENV === 'production') {
app.set('trust proxy', 1)
}

// view engine setup
app.set("views", path.join(__dirname, "views"));
app.engine(".hbs", hbs.engine);
app.set("view engine", ".hbs");
app.set('views', path.join(__dirname, 'views'))
app.engine('.hbs', hbs.engine)
app.set('view engine', '.hbs')

app.use(logger("dev"));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, "public")));
app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))

app.use(
"/internal",
'/internal',
(req, res, next) => {
next();
next()
},
internalRouter
);
internalRouter,
)

// create a middleware to capture domain slug
app.use(async (req, res, next) => {
Expand All @@ -113,81 +118,75 @@ app.use(async (req, res, next) => {
// if domain slug is found, then set it in res.locals.domainSlug
// then call next()

if (!!Number(process.env.DEBUG)) {
res.locals.domainSlug = req.query[process.env.DOMAIN_QUERY_PARAM] || "";
if (Number(process.env.DEBUG)) {
res.locals.domainSlug = req.query[process.env.DOMAIN_QUERY_PARAM] || ''
} else if (req.hostname) {
// check if the domain is part of root domain or is it a custom domain
// if it is a custom domain, then set res.locals.customDomain to true
// else set it to false

// split the hostname at the first dot
const dotIndex = req.hostname.indexOf(".");
const firstPart = req.hostname.slice(0, dotIndex);
const secondPart = req.hostname.slice(dotIndex + 1);
const dotIndex = req.hostname.indexOf('.')
const firstPart = req.hostname.slice(0, dotIndex)
const secondPart = req.hostname.slice(dotIndex + 1)

if (secondPart === process.env.ROOT_DOMAIN) {
res.locals.customDomain = false;
res.locals.customDomain = false

res.locals.domainSlug = firstPart;
res.locals.domainSlug = firstPart

if (res.locals.domainSlug === "publish") {
res.locals.domainSlug = req.query[process.env.DOMAIN_QUERY_PARAM];
if (res.locals.domainSlug === 'publish') {
res.locals.domainSlug = req.query[process.env.DOMAIN_QUERY_PARAM]
}
} else {
res.locals.customDomain = true;
res.locals.domainSlug = req.hostname;
res.locals.customDomain = true
res.locals.domainSlug = req.hostname
}
}

console.log(
"A",
req.hostname,
res.locals.customDomain,
res.locals.domainSlug
);

if (!res.locals.domainSlug) {
res.locals.domainSlug = "";
next();
res.locals.domainSlug = ''
next()
} else {
next();
next()
}
});
})

// Sitemap
app.get("/sitemap.xml", (req, res) => {
app.get('/sitemap.xml', (req, res) => {
// genSitemap().then((d) => {
// res.set("Content-Type", "text/xml");
// res.type("application/xml");
// res.send(d);
// });
});
})

app.use("/", indexRouter);
app.use('/', indexRouter)

// // catch 404 and forward to error handler
// app.use(function (req, res, next) {
// next(createError(404));
// });

// Run a CRON that runs every 6 hours cacheUsersData
cron.schedule("0 */6 * * *", () => {
console.log("Running a task every 6 hours");
cacheUsers();
cacheNotes();
});
cacheUsers();
cacheNotes();
cron.schedule('0 */6 * * *', () => {
// eslint-disable-next-line no-console
console.log('Running a task every 6 hours')
cacheUsers()
cacheNotes()
})
cacheUsers()
cacheNotes()

// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get("env") === "development" ? err : {};
res.locals.message = err.message
res.locals.error = req.app.get('env') === 'development' ? err : {}

// render the error page
res.status(err.status || 500);
res.status(err.status || 500)
// res.render("error");
});
})

module.exports = app;
module.exports = app
8 changes: 4 additions & 4 deletions publisher/constants.js
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
const BLOG_CATEGORIES = ["blog", "product", "help", "guides"];
const GHOST_API_KEY = "3ed1f08bc38fe9e7dfd325bd87";
const GHOST_URL = "https://blog-admin.btw.so";
const BLOG_CATEGORIES = ['blog', 'product', 'help', 'guides']
const GHOST_API_KEY = '3ed1f08bc38fe9e7dfd325bd87'
const GHOST_URL = 'https://blog-admin.btw.so'

module.exports = {
BLOG_CATEGORIES,
GHOST_API_KEY,
GHOST_URL,
};
}
Loading