api drop unused code

This commit is contained in:
tmshv committed 2020-03-03 01:33:17 +03:00
1 parent d859fdb302
commit 06745b45f4
26 files changed
+32 -788

No files matched your search

@@ -1,54 +0,0 @@
import Article from '../core/Article'
import { findArticles } from '../server/articles'
import { Request, Response } from 'express'
import { encodeArticle } from '../factory/article'
import { readQueryInt } from '../lib/url'
export async function getItem(req: Request, res: Response) {
const id = req.params.slug
const article = await Article.findById(id)
if (article) {
res.json(encodeArticle(article))
} else {
res.status(404)
res.json({
error: `Resource ${id} not found`
})
}
}
export async function getAll(req: Request, res: Response) {
const page = readQueryInt(req, 'page')
const pageSize = readQueryInt(req, 'pageSize')
const data = await findArticles(page, pageSize)
if (data) {
res.json({
...data,
items: data.items.map(encodeArticle)
})
} else {
res.status(404)
res.json({
error: `Articles not found`
})
}
}
export async function getUrls(req: Request, res: Response) {
const data = await Article.find({})
if (data) {
const items = data.map(x => `/article/${x.id}`)
res.json({
items
})
} else {
res.status(404)
res.json({
error: `Not found`
})
}
}
+4 -2
View File
@@ -10,8 +10,10 @@ function getSort(sortBy: string) {
}
if (sortBy.charAt(0) === '-') {
const key = sortBy.substr(1, sortBy.length)
return {
[sortBy.substr(1, sortBy.length)]: -1,
[key]: -1,
}
}
@@ -73,7 +75,7 @@ export async function getByTags(req: Request, res: Response) {
const options = { skip, limit, sort }
const models = await Page.find({
tags: { $in: ['event', 'album'] },
tags: { $in: tags },
}, options)
if (models) {
@@ -1,18 +0,0 @@
import { findSchedule } from '../server/schedule'
import { Request, Response } from 'express'
import { collection } from '../db'
export async function getItem(req: Request, res: Response) {
const period = req.query.period
const semester = req.query.semester
const data = await findSchedule(collection, period, semester)
if (data) {
res.json(data)
} else {
res.status(404)
res.json({
error: `Schedule ${period}:${semester} not found`
})
}
}
+3 -3
View File
@@ -1,9 +1,9 @@
import Article from '../core/Article'
import Page from '../core/Page'
import { Request, Response } from 'express'
import { unique } from '../lib/array'
export async function getAll(req: Request, res: Response) {
const data = await Article.find({})
const data = await Page.find({})
const tags = data
.flatMap(x => x.tags)
.filter(x => x.isValid())
@@ -24,7 +24,7 @@ export async function getAll(req: Request, res: Response) {
export async function findItems(req: Request, res: Response) {
const slug = req.params.slug
const data = await Article.find({
const data = await Page.find({
tags: {
}
-116
View File
@@ -1,116 +0,0 @@
import Data from './Data'
import Image from './Image'
import { find, findOne, total } from '../lib/store'
import { Tag } from './Tag'
const store = () => Data.getStore<Article>('Article')
export default class Article {
static async find(query, options = {}): Promise<Article[]> {
const items = await find(store(), query, options as any)
return Promise.all(items.map(processArticle))
}
static async findById(id) {
const item = await findOne(store(), { id })
return !item
? null
: processArticle(item)
}
static async total(query = {}) {
return total(store(), query)
}
static async findPinned() {
const now = new Date()
const query = { until: { $gte: now } }
return Article.find(query, {
sort: { date: -1 },
})
}
public id: any
public images: any
public post: any
public folder: any
public date: any
public title: any
public until: any
public tags: Tag[]
public content: any
public hash: any
public type: any
public origin: any
public file: any
public version: any
public preview: any
public url: any
public featured: boolean
constructor(data) {
this.id = data.id
this.images = data.images
this.post = data.post
this.folder = data.folder
this.date = data.date
this.title = data.title
this.until = data.until
this.tags = (data.tags || []).map((x: string) => Tag.fromCyrillic(x))
this.content = data.content
this.hash = data.hash
this.type = data.type
this.origin = data.origin
this.file = data.file
this.version = data.version
this.preview = data.preview
this.featured = data.featured || false
this.url = `/article/${this.id}`
}
// plain() {
// return {
// id: this.id,
// images: this.images,
// post: this.post,
// folder: this.folder,
// date: this.date,
// title: this.title,
// until: this.until,
// tags: this.tags,
// content: this.content,
// hash: this.hash,
// type: this.type,
// origin: this.origin,
// file: this.file,
// version: this.version,
// preview: this.preview,
// url: this.url,
// featured: this.featured,
// }
// }
}
const previewFromImage = (imgs = []) => imgs.length
? imgs[0]
: null
async function processArticle(article) {
let preview = null
const previewId = article.preview
? article.preview
: previewFromImage(article.images)
if (previewId) {
preview = await Image.findById(previewId)
}
return new Article({
...article,
preview,
})
}
+15 -1
View File
@@ -1,9 +1,23 @@
import Data from './Data'
import ImageArtifactType from './ImageArtifactType'
import { findOne } from '../lib/store'
import { mapOf } from '../server/lib'
import { ObjectId } from 'mongodb'
/**
*
* {a: {}, b: {}, ...} -> Map (a: Class, b: Class)
*
* @param Class
* @param object
*/
function mapOf(Class, object) {
return Object
.entries(object)
.reduce((map, i) => (
map.set(i[0], new Class(i[1]))
), new Map())
}
const store = () => Data.getStore('Image')
export default class Image {
-1
View File
@@ -27,7 +27,6 @@ function init(db: Db) {
console.log('INIT DB')
Data.setStore('Page', db.collection('pages'))
Data.setStore('Article', db.collection('articles'))
Data.setStore('Image', db.collection('images'))
Data.setStore('Document', db.collection('documents'))
Data.setStore('Settings', db.collection('settings'))
@@ -1,11 +0,0 @@
import Article from '../core/Article'
import { encodeImage } from './image'
export function encodeArticle(article: Article) {
const preview = article.preview ? encodeImage(article.preview) : null
return {
...article,
preview,
}
}
-7
View File
@@ -1,7 +0,0 @@
/**
*
* Date -> Unix time
*
* @param date
*/
export const timestamp = (date: Date) => date.getTime()
-23
View File
@@ -1,23 +0,0 @@
const getExt = (name: string) => /\.(\w+)$/.exec(name)[1]
const defaultExt = (ext: string) => ext.toUpperCase()
const exts = ['png', 'pdf', 'jpg', 'jpeg', 'gif', 'doc']
const extd = ['ПНГ', 'ПДФ', 'ЖПГ', 'ЖПГ', 'ГИФ', 'ДОК']
const units = ['байт', 'КБ', 'МБ', 'ГБ', 'ТБ', 'ПБ']
export function ext(filname: string): string {
const ext = getExt(filname)
const i = exts.indexOf(ext)
return i > -1
? extd[i]
: defaultExt(ext)
}
export function size(bytes: any, precision = 1): string {
if (isNaN(parseFloat(bytes)) || !isFinite(bytes)) return ''
const number = Math.floor(Math.log(bytes) / Math.log(1024))
const size = (bytes / Math.pow(1024, Math.floor(number))).toFixed(precision)
return `${size} ${units[number]}`
}
-22
View File
@@ -1,22 +0,0 @@
function sort(list, fn, reverse = false) {
return list
.map(i => [fn(i), i])
.sort((a, b) => reverse
? a[0] - b[0]
: b[0] - a[0])
.map(i => i[1])
}
function sortBy(fn, reverse = false) {
return (i1, i2) => {
const t1 = fn(i1)
const t2 = fn(i2)
return reverse
? t1 - t2
: t2 - t1
}
}
exports.sortBy = sortBy
exports.sort = sort
+10 -10
View File
@@ -1,19 +1,19 @@
export async function find(collection, query, {sort, skip, limit}) {
const cursor = collection.find(query)
export async function find(collection, query, { sort, skip, limit }) {
const cursor = collection.find(query)
if (sort) cursor.sort(sort)
if (skip) cursor.skip(skip)
if (limit) cursor.limit(limit)
if (sort) cursor.sort(sort)
if (skip) cursor.skip(skip)
if (limit) cursor.limit(limit)
return cursor.toArray()
return cursor.toArray()
}
export async function findOne(collection, query) {
return collection.findOne(query)
return collection.findOne(query)
}
export async function total(collection, query) {
return collection
.find(query)
.count()
return collection
.find(query)
.count()
}
-12
View File
@@ -1,12 +0,0 @@
function titleCase(str) {
return str.charAt(0).toUpperCase() + str.slice(1)
}
function trim(string) {
return string
.replace(/^\s+/, '')
.replace(/\s+$/, '')
}
exports.titleCase = titleCase
exports.trim = trim
-22
View File
@@ -1,22 +0,0 @@
const courses = {
painting: ['Живопись', ''],
drawing: ['Рисунок', '/courses/drawing'],
sculpting: ['Скульптура', ''],
sculpture: ['Скульптура', ''],
ceramic: ['Керамика', '/courses/ceramics'],
ceramics: ['Керамика', '/courses/ceramics'],
composition: ['Композиция', ''],
'easel-composition': ['Станковая композиция', ''],
dpi: ['ДПИ', ''],
'art-talks': ['Беседа по искусству', ''],
history: ['История искусства', '/courses/art-history'],
cg: ['Комп. графика', '/courses/cg'],
}
export function getCourse(id) {
const course = id in courses ? courses[id] : null
if (!course) return null
const [title, url] = course
return {id, title, url}
}
@@ -1,44 +0,0 @@
export const autumnMonth = 8;
export const springMonth = 0;
export function scheduleDate(schedule){
let {period, semester} = schedule;
let i = semester === 'spring' ? 1 : 0;
let year = getPeriod(period)[i];
return new Date(
year,
i ? springMonth : autumnMonth,
1
);
}
/**
*
* f("2012-2015") -> [2012, 2015]
* f(["2012", "2015"]) -> [2012, 2015]
* f([2012, 2015]) -> [2012, 2015]
*
* @param i
* @returns {*}
*/
export function getPeriod(i){
if (typeof i === 'string') return getPeriod(i.split('-'));
return i.map(Number);
}
/**
*
* f("2012-2015") -> "2012-2015"
* f(["2012", "2015"]) -> "2012-2015"
* f([2012, 2015]) -> "2012-2015"
*
* @param i
* @returns {*}
*/
export function getPeriodString(i) {
return getPeriod(i)
.join('-')
}
-7
View File
@@ -1,8 +1,6 @@
import { config } from 'dotenv'
import express from 'express'
import { connect } from './db'
import * as article from './controllers/article'
import * as schedule from './controllers/schedule'
import * as file from './controllers/file'
import * as page from './controllers/page'
import * as image from './controllers/image'
@@ -23,10 +21,6 @@ async function main() {
}
const app = express()
app.get('/articles', article.getAll)
app.get('/articles/urls', article.getUrls)
app.get('/articles/:slug', article.getItem)
app.get('/files', file.getAll)
app.get('/files/urls', file.getUrls)
app.get('/files/:slug', file.getItem)
@@ -38,7 +32,6 @@ async function main() {
app.get('/image', image.getItem)
app.get('/schedule', schedule.getItem)
app.get('/tags', tag.getAll)
app.get('/tags/:slug', tag.findItems)
@@ -1,56 +0,0 @@
import Article from '../core/Article'
import ImageArtifactType from '../core/ImageArtifactType'
import { sortBy } from '../utils/sort'
import { timestamp } from '../lib/date'
export const sortArticleByDate = sortBy(
x => timestamp(new Date(x.date))
)
export async function findArticlesNin(nin, skip, limit, sort) {
const query = {
_id: { $nin: nin }
}
return Article.find(query, {
sort,
skip,
limit,
})
}
export async function findArticles(page: number, pageSize: number) {
const limit = pageSize
const skip = (page - 1) * pageSize
// const pinnedArticles = page === 1
// ? await Article.findPinned()
// : []
const total = await Article.total()
const totalPages = Math.ceil(total / pageSize)
const id = i => i._id
// const pinnedIds = pinnedArticles.map(id)
// const articles = await findArticlesNin(pinnedIds, skip, limit, { date: -1 })
const articles = await Article.find({}, { skip, limit, sort: { date: -1 } })
const prevPage = page > 1
? page - 1
: null
const nextPage = page < totalPages
? page + 1
: null
const items = [
...articles
]
return {
items,
prevPage,
nextPage,
totalPages,
}
}
-14
View File
@@ -1,14 +0,0 @@
/**
*
* {a: {}, b: {}, ...} -> Map (a: Class, b: Class)
*
* @param Class
* @param object
*/
export function mapOf(Class, object) {
return Object
.entries(object)
.reduce((map, i) => (
map.set(i[0], new Class(i[1]))
), new Map())
}
-134
View File
@@ -1,134 +0,0 @@
import { createMap } from '../utils/common'
import {
scheduleDate,
getPeriod as schedulePeriod,
getPeriodString
} from '../models/schedule'
import { getCourse } from '../models/course'
// import { last } from 'lodash'
// const sortBy = require('../lib/sort').sortBy
const SCHEDULES = 'schedules'
export async function findSchedule(collection, period, semester) {
const schedule = await collection(SCHEDULES).findOne({
$or: [
{ period: period },
{ period: schedulePeriod(period) }
],
semester: semester
})
return schedule ? migrate(schedule) : null
}
// async function findAllScheduleParams() {
// const schedules = await collection(SCHEDULES)
// .find({}, {
// period: 1,
// semester: 1,
// _id: 0,
// })
// .toArray()
// return schedules
// .map(i => ({
// ...i,
// period: schedulePeriod(i.period),
// }))
// .sort(sortBy(
// i => scheduleDate(i).getTime(),
// true,
// ))
// }
// function text({ semester, period }) {
// const word = semester => [['spring', 'Весна'], ['autumn', 'Осень']]
// .find(i => i[0] === semester)
// [1]
// const periodIndex = semester === 'spring' ? 1 : 0
// const year = period[periodIndex]
// return `${word(semester)} ${year} года`
// }
async function migrate(schedule) {
const versions = {
'1.0': migrate10to20,
'2.0': migrate20to30,
}
const version = schedule.version
const update = versions[version]
return version in versions ? migrate(update(schedule)) : schedule
}
function migrate10to20(schedule) {
const dayNames = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat', 'sun']
const time = time => time
.map(i => i.split(' '))
const week = days => days.reduce((week, lesson, index) => {
if (lesson) {
const day = dayNames[index]
week[day] = [Object.assign(lesson, {
time: time(lesson.time)
})]
}
return week
}, {})
return Object.assign(schedule, {
version: '2.0',
period: schedulePeriod(schedule.period),
groups: schedule.schedule
.map(group => ({
name: group.group,
time: group.time,
week: week(group.week)
}))
})
}
async function migrate20to30(schedule) {
const days = ['mon', 'tue', 'wed', 'thu', 'fri', 'sat']//, 'sun']
const persons = []
const person = createMap(i => i.id, persons)
const week = week => days
.map(day => week[day] || [])
.map(lessons => lessons.map(lesson))
const lesson = i => ({
time: i.time,
course: getCourse(i.lesson),
teacher: person.has(i.teacher) ? teacher(i.teacher) : teacherDummy(i.teacher)
})
const teacher = id => ({
id: id,
url: `/teacher/${id}`,
name: personName(id)
})
const teacherDummy = name => ({
id: name,
url: null,
name: name
})
const personName = id => person.has(id) ? person.get(id).name : null
return Object.assign(schedule, {
version: '3.0',
groups: schedule.groups
.map(group => ({
name: group.name,
time: group.time,
week: week(group.week)
}))
})
}
-106
View File
@@ -1,106 +0,0 @@
/**
* Generates list of numbers
* @param {Number} start starting value
* @param {Number} num amount of numbers in list
* @param {Number} step difference value
* @return {Array} list of numbers
*/
export function range(start, num, step) {
var list = [];
var val = start;
for (var i = 0; i < num; i++) {
list.push(val);
val += step;
}
return list;
}
/**
* Return a closure that compares a Number argument with specified Number
* @param withNumber Number to compare with
* @returns {Function} (i) => {}
*/
export function numberEquals(withNumber) {
return i => i === withNumber;
}
/**
* Return a closure that compares a second Number argument with specified Number
* @param withNumber Number to compare with
* @returns {Function} (i) => {}
*/
export function indexEquals(withNumber) {
return (_, i) => i === withNumber;
}
/**
* Return a reduce function
* [['spring', 'Весена'], ['autumn', 'Осень']] -> 'Весна' or 'Осень' depend on byCondition result
* @param byCondition
* @param map
*/
export function select(byCondition, map = i => i) {
return (result, item) => byCondition(item) ? map(item) : map(result)
}
/**
* Select an item in Array by specified selector function
* @param scope
* @param selector
* @returns {*}
*/
export function choise(scope, selector) {
return scope.reduce(selector, null);
}
export function unique<T, U>(fn: (value: T) => U): (list: T[]) => U[] {
return list => Array.from(
new Set(list.map(fn))
)
}
export function branch(fn) {
let keys = unique(fn);
return list => keys(list)
.reduce((dict: any, key: any) => {
dict[key] = list.filter(
i => fn(i) === key
);
return dict;
}, {})
}
export function assign(dict, key, value) {
dict[key] = value;
return dict;
}
export function map(v, fn) {
return value => fn(value) ? v : value;
}
/**
*
* f(g, [x, y, z, ...]) => map of {g(x): x, g(y): y, g(z): z}
*
* @param list
* @param selector
* @returns {*}
*/
export function createMap(selector, list) {
return list.reduce((map, i) => map.set(selector(i), i), new Map());
}
/**
*
* f(g) => x ? g(x) : null
*
* @param {function} fn
* @returns {function(*=): null}
*/
export function nullSafe(fn) {
return i => i ? fn(i) : null;
}
-21
View File
@@ -1,21 +0,0 @@
import {range} from './common';
/**
*
* @param start
* @returns {*}
*/
export function getDates(start) {
const oneDay = (1000 * 60 * 60 * 24);
const startTime = start.getTime();
const startDay = start.getDay();
return range(0, 6, 1)
.reduce((dates, weekDay) => {
let delta = 1 + weekDay - startDay;
let time = startTime + (oneDay * delta);
return dates.concat([new Date(time)]);
}, [])
.map(i => i.getDate());
}
-13
View File
@@ -1,13 +0,0 @@
/**
*
* f([x, y, z, ...]) -> f(v) -> {v.x, v.y, v.z}
*
* @param fields
* @returns {function(*): *}
*/
export function select(fields=[]){
return i => fields.reduce((out, key) => {
out[key] = i[key];
return out;
}, {});
}
-8
View File
@@ -1,8 +0,0 @@
export function query(list) {
return list
.reduce(
(query, param) => query.concat([`${param[0]}=${param[1]}`]),
[]
)
.join('&');
}
-35
View File
@@ -1,35 +0,0 @@
export function pop(data){
var Populator = function(data){
this.target = data;
}
Populator.prototype = {
populate: function(p){
var self = this;
if(typeof p == "function"){
self.target = p(self.target);
}else if(p instanceof Array){
p.forEach(function(i){
self.target = self.populate(i).result();
});
}
return self;
},
result: function(){
return this.target;
}
};
var fun = new Populator(data);
return fun;
}
export function populate(fn, key){
return (dict) => {
let id = dict[key];
let value = fn(id);
dict[key] = value ? value : id;
return dict;
}
}
-26
View File
@@ -1,26 +0,0 @@
export function sortByPattern(list, pattern, map) {
let weight = i => {
const index = pattern.indexOf(map(i))
return index > -1 ? pattern.length - index : 0
}
return sortByWeight(list, weight)
}
export function sortByWeight(list, fn) {
return list
.map(i => [fn(i), i])
.sort((a, b) => b[0] - a[0])
.map(i => i[1])
}
export function sortBy(fn) {
return (i1, i2) => {
let t1 = fn(i1)
let t2 = fn(i2)
if (t1 < t2) return 1
if (t1 > t2) return -1
return 0
}
}
-22
View File
@@ -1,22 +0,0 @@
import {map} from './common';
/**
* Return a function that accept one String parameter and returns result of replacing.
*
* @param searchValue
* @param replaceValue
*/
export const stringReplace = (searchValue, replaceValue) =>
str => str.replace(searchValue, replaceValue);
let toTrue = map(true, i => i === 'true');
let toFalse = map(false, i => i === 'false');
const boolProcessors = [toTrue, toFalse];
export function stringToBoolean(string){
return boolProcessors
.reduce(
(value, fn) => fn(value),
string
);
}