1
0
Fork 0
mirror of https://github.com/seejohnrun/haste-server.git synced 2024-11-01 11:31:22 +00:00

add prettier

This commit is contained in:
Yusuf Yilmaz 2022-06-06 19:44:11 +02:00
parent 21aa23dd28
commit a5b0a98b3f
19 changed files with 94 additions and 92 deletions

View file

@ -80,6 +80,7 @@
"dev": "nodemon src/server.ts", "dev": "nodemon src/server.ts",
"start": "node dist/src/server.js", "start": "node dist/src/server.js",
"lint": "eslint src --fix", "lint": "eslint src --fix",
"types:check": "tsc --noEmit --pretty" "types:check": "tsc --noEmit --pretty",
"pretty": "prettier --write src"
} }
} }

View file

@ -1,5 +1,5 @@
const DEFAULT_KEY_LENGTH = 10 const DEFAULT_KEY_LENGTH = 10
export default { export default {
DEFAULT_KEY_LENGTH, DEFAULT_KEY_LENGTH
} }

9
src/global.d.ts vendored
View file

@ -30,11 +30,11 @@ declare module 'rethinkdbdash' {
declare module 'connect-ratelimit' { declare module 'connect-ratelimit' {
function connectRateLimit( function connectRateLimit(
as: RateLimits, as: RateLimits
): ( ): (
req: express.Request, req: express.Request,
res: express.Response, res: express.Response,
next: express.NextFunction, next: express.NextFunction
) => void ) => void
export = connectRateLimit export = connectRateLimit
@ -47,11 +47,10 @@ declare namespace Express {
} }
declare module 'st' { declare module 'st' {
type ConnectSt = { type ConnectSt = {
path: string path: string
content: { maxAge : number } content: { maxAge: number }
passthrough? : boolean passthrough?: boolean
index: boolean | string index: boolean | string
} }

View file

@ -1,7 +1,7 @@
import buildGenerator from 'src/lib/key-generators/builder' import buildGenerator from 'src/lib/key-generators/builder'
import type { Config } from 'src/types/config' import type { Config } from 'src/types/config'
import buildStore from 'src/lib/document-stores/builder' import buildStore from 'src/lib/document-stores/builder'
import DocumentHandler from "./index" import DocumentHandler from './index'
const build = async (config: Config) => { const build = async (config: Config) => {
const storage = await buildStore(config) const storage = await buildStore(config)
@ -12,7 +12,7 @@ const build = async (config: Config) => {
config, config,
maxLength: config.maxLength, maxLength: config.maxLength,
keyLength: config.keyLength, keyLength: config.keyLength,
keyGenerator, keyGenerator
}) })
return documentHandler return documentHandler

View file

@ -51,7 +51,7 @@ class DocumentHandler {
} }
} }
}, },
skipExpire, skipExpire
) )
} }
@ -68,7 +68,7 @@ class DocumentHandler {
winston.warn('document >maxLength', { maxLength: this.maxLength }) winston.warn('document >maxLength', { maxLength: this.maxLength })
response.writeHead(400, { 'content-type': 'application/json' }) response.writeHead(400, { 'content-type': 'application/json' })
response.end( response.end(
JSON.stringify({ message: 'Document exceeds maximum length.' }), JSON.stringify({ message: 'Document exceeds maximum length.' })
) )
return return
} }
@ -131,7 +131,7 @@ class DocumentHandler {
if (ret) { if (ret) {
winston.verbose('retrieved raw document', { key }) winston.verbose('retrieved raw document', { key })
response.writeHead(200, { response.writeHead(200, {
'content-type': 'text/plain; charset=UTF-8', 'content-type': 'text/plain; charset=UTF-8'
}) })
if (request.method === 'HEAD') { if (request.method === 'HEAD') {
response.end() response.end()
@ -148,7 +148,7 @@ class DocumentHandler {
} }
} }
}, },
skipExpire, skipExpire
) )
} }
@ -166,7 +166,7 @@ class DocumentHandler {
callback(key) callback(key)
} }
}, },
true, true
) // Don't bump expirations when key searching ) // Don't bump expirations when key searching
} }

View file

@ -22,7 +22,7 @@ class AmazonS3DocumentStore implements Store {
get = ( get = (
key: string, key: string,
callback: Callback, callback: Callback,
skipExpire?: boolean | undefined, skipExpire?: boolean | undefined
): void => { ): void => {
if (!this.bucket) { if (!this.bucket) {
callback(false) callback(false)
@ -31,7 +31,7 @@ class AmazonS3DocumentStore implements Store {
const req = { const req = {
Bucket: this.bucket, Bucket: this.bucket,
Key: key, Key: key
} }
this.client.getObject(req, (err, data) => { this.client.getObject(req, (err, data) => {
@ -50,7 +50,7 @@ class AmazonS3DocumentStore implements Store {
key: string, key: string,
data: string, data: string,
callback: Callback, callback: Callback,
skipExpire?: boolean | undefined, skipExpire?: boolean | undefined
): void => { ): void => {
if (!this.bucket) { if (!this.bucket) {
callback(false) callback(false)
@ -61,7 +61,7 @@ class AmazonS3DocumentStore implements Store {
Bucket: this.bucket, Bucket: this.bucket,
Key: key, Key: key,
Body: data as AWS.S3.PutObjectOutput, Body: data as AWS.S3.PutObjectOutput,
ContentType: 'text/plain', ContentType: 'text/plain'
} }
this.client.putObject(req, err => { this.client.putObject(req, err => {

View file

@ -33,7 +33,7 @@ class FileDocumentStore implements Store {
get = ( get = (
key: string, key: string,
callback: Callback, callback: Callback,
skipExpire?: boolean | undefined, skipExpire?: boolean | undefined
): void => { ): void => {
const fn = `${this.basePath}/${md5(key)}` const fn = `${this.basePath}/${md5(key)}`
fs.readFile(fn, 'utf8', (err, data) => { fs.readFile(fn, 'utf8', (err, data) => {
@ -54,7 +54,7 @@ class FileDocumentStore implements Store {
key: string, key: string,
data: string, data: string,
callback: Callback, callback: Callback,
skipExpire?: boolean | undefined, skipExpire?: boolean | undefined
): void => { ): void => {
try { try {
fs.mkdir(this.basePath, '700', () => { fs.mkdir(this.basePath, '700', () => {

View file

@ -26,7 +26,7 @@ class GoogleDatastoreDocumentStore implements Store {
key: PathType, key: PathType,
data: string, data: string,
callback: Callback, callback: Callback,
skipExpire?: boolean, skipExpire?: boolean
) => { ) => {
const expireTime = const expireTime =
skipExpire || this.expire === undefined skipExpire || this.expire === undefined
@ -40,13 +40,13 @@ class GoogleDatastoreDocumentStore implements Store {
{ {
name: 'value', name: 'value',
value: data, value: data,
excludeFromIndexes: true, excludeFromIndexes: true
}, },
{ {
name: 'expiration', name: 'expiration',
value: expireTime, value: expireTime
}, }
], ]
} }
this.datastore this.datastore
@ -72,7 +72,7 @@ class GoogleDatastoreDocumentStore implements Store {
winston.info('document expired', { winston.info('document expired', {
key, key,
expiration: entity[0].expiration, expiration: entity[0].expiration,
check: new Date(), check: new Date()
}) })
callback(false) callback(false)
} else { } else {
@ -83,15 +83,15 @@ class GoogleDatastoreDocumentStore implements Store {
{ {
name: 'value', name: 'value',
value: entity[0].value, value: entity[0].value,
excludeFromIndexes: true, excludeFromIndexes: true
}, },
{ {
name: 'expiration', name: 'expiration',
value: new Date( value: new Date(
Date.now() + (this.expire ? this.expire * 1000 : 0), Date.now() + (this.expire ? this.expire * 1000 : 0)
), )
}, }
], ]
} }
this.datastore this.datastore
.update(task) .update(task)
@ -104,7 +104,7 @@ class GoogleDatastoreDocumentStore implements Store {
}) })
.catch(err => { .catch(err => {
winston.error('Error retrieving value from Google Datastore', { winston.error('Error retrieving value from Google Datastore', {
error: err, error: err
}) })
callback(false) callback(false)
}) })

View file

@ -36,7 +36,7 @@ class MemcachedDocumentStore implements Store {
get = ( get = (
key: string, key: string,
callback: Callback, callback: Callback,
skipExpire?: boolean | undefined, skipExpire?: boolean | undefined
): void => { ): void => {
this.client?.get(key, (error, data: string) => { this.client?.get(key, (error, data: string) => {
const value = error ? false : data const value = error ? false : data
@ -53,7 +53,7 @@ class MemcachedDocumentStore implements Store {
winston.error('failed to update expiration on GET', { key }) winston.error('failed to update expiration on GET', { key })
} }
}, },
skipExpire, skipExpire
) )
} }
}) })
@ -64,7 +64,7 @@ class MemcachedDocumentStore implements Store {
key: string, key: string,
data: string, data: string,
callback: Callback, callback: Callback,
skipExpire?: boolean | undefined, skipExpire?: boolean | undefined
): void => { ): void => {
this.client?.set(key, data, skipExpire ? 0 : this.expire || 0, error => { this.client?.set(key, data, skipExpire ? 0 : this.expire || 0, error => {
callback(!error) callback(!error)

View file

@ -33,7 +33,7 @@ class MongoDocumentStore implements Store {
get = ( get = (
key: string, key: string,
callback: Callback, callback: Callback,
skipExpire?: boolean | undefined, skipExpire?: boolean | undefined
): void => { ): void => {
const now = Math.floor(new Date().getTime() / 1000) const now = Math.floor(new Date().getTime() / 1000)
@ -46,7 +46,7 @@ class MongoDocumentStore implements Store {
.findOne( .findOne(
{ {
entry_id: key, entry_id: key,
$or: [{ expiration: -1 }, { expiration: { $gt: now } }], $or: [{ expiration: -1 }, { expiration: { $gt: now } }]
}, },
(error?: Error, entry?) => { (error?: Error, entry?) => {
if (error) { if (error) {
@ -67,20 +67,20 @@ class MongoDocumentStore implements Store {
.collection('entries') .collection('entries')
.update( .update(
{ {
entry_id: key, entry_id: key
}, },
{ {
$set: { $set: {
expiration: this.expire + now, expiration: this.expire + now
}, }
}, },
{}, {},
() => {}, () => {}
) )
} }
return true return true
}, }
) )
}) })
} }
@ -89,7 +89,7 @@ class MongoDocumentStore implements Store {
key: string, key: string,
data: string, data: string,
callback: Callback, callback: Callback,
skipExpire?: boolean | undefined, skipExpire?: boolean | undefined
): void => { ): void => {
const now = Math.floor(new Date().getTime() / 1000) const now = Math.floor(new Date().getTime() / 1000)
@ -102,15 +102,15 @@ class MongoDocumentStore implements Store {
.update( .update(
{ {
entry_id: key, entry_id: key,
$or: [{ expiration: -1 }, { expiration: { $gt: now } }], $or: [{ expiration: -1 }, { expiration: { $gt: now } }]
}, },
{ {
entry_id: key, entry_id: key,
value: data, value: data,
expiration: this.expire && !skipExpire ? this.expire + now : -1, expiration: this.expire && !skipExpire ? this.expire + now : -1
}, },
{ {
upsert: true, upsert: true
}, },
(error?: Error) => { (error?: Error) => {
if (error) { if (error) {
@ -119,7 +119,7 @@ class MongoDocumentStore implements Store {
} }
return callback(true) return callback(true)
}, }
) )
}) })
} }

View file

@ -7,7 +7,7 @@ import type { PostgresStoreConfig } from 'src/types/config'
type ConnectCallback = ( type ConnectCallback = (
error?: Error, error?: Error,
client?: PoolClient, client?: PoolClient,
done?: () => void, done?: () => void
) => void ) => void
// A postgres document store // A postgres document store
@ -42,7 +42,7 @@ class PostgresDocumentStore implements Store {
get = ( get = (
key: string, key: string,
callback: Callback, callback: Callback,
skipExpire?: boolean | undefined, skipExpire?: boolean | undefined
): void => { ): void => {
const now = Math.floor(new Date().getTime() / 1000) const now = Math.floor(new Date().getTime() / 1000)
this.safeConnect((err, client, done): void => { this.safeConnect((err, client, done): void => {
@ -56,7 +56,7 @@ class PostgresDocumentStore implements Store {
(error: Error, result) => { (error: Error, result) => {
if (error) { if (error) {
winston.error('error retrieving value from postgres', { winston.error('error retrieving value from postgres', {
error, error
}) })
return callback(false) return callback(false)
} }
@ -71,12 +71,12 @@ class PostgresDocumentStore implements Store {
} }
return callback(false) return callback(false)
}, }
) )
} }
return done?.() return done?.()
}, }
) )
}) })
} }
@ -86,7 +86,7 @@ class PostgresDocumentStore implements Store {
key: string, key: string,
data: string, data: string,
callback: Callback, callback: Callback,
skipExpire?: boolean | undefined, skipExpire?: boolean | undefined
): void => { ): void => {
const now = Math.floor(new Date().getTime() / 1000) const now = Math.floor(new Date().getTime() / 1000)
this.safeConnect((err, client, done) => { this.safeConnect((err, client, done) => {
@ -103,7 +103,7 @@ class PostgresDocumentStore implements Store {
} }
callback(true) callback(true)
return done?.() return done?.()
}, }
) )
}) })
} }

View file

@ -35,18 +35,20 @@ class RedisDocumentStore implements Store {
const port = options.port || 6379 const port = options.port || 6379
const index = options.db || 0 const index = options.db || 0
const connectionParameters = url ? { const connectionParameters = url
url ? {
}: { url
host, }
port : {
} host,
port
}
const config = { const config = {
...connectionParameters, ...connectionParameters,
database: index as number, database: index as number,
...(options.username ? { username: options.username } : {}), ...(options.username ? { username: options.username } : {}),
...(options.password ? { username: options.username } : {}), ...(options.password ? { username: options.username } : {})
} }
this.client = createClient(config) this.client = createClient(config)
@ -63,7 +65,7 @@ class RedisDocumentStore implements Store {
}) })
.catch(err => { .catch(err => {
winston.error(`error connecting to redis index ${index}`, { winston.error(`error connecting to redis index ${index}`, {
error: err, error: err
}) })
process.exit(1) process.exit(1)
}) })
@ -86,7 +88,7 @@ class RedisDocumentStore implements Store {
key: string, key: string,
data: string, data: string,
callback: Callback, callback: Callback,
skipExpire?: boolean | undefined, skipExpire?: boolean | undefined
): void => { ): void => {
this.client this.client
?.set(key, data, this.getExpire(skipExpire)) ?.set(key, data, this.getExpire(skipExpire))

View file

@ -22,7 +22,7 @@ class RethinkDBStore {
port: options.port || 28015, port: options.port || 28015,
db: options.db || 'haste', db: options.db || 'haste',
user: options.user || 'admin', user: options.user || 'admin',
password: options.password || '', password: options.password || ''
}) })
} }

View file

@ -7,7 +7,7 @@ const getConfig = (): Config => {
const configPath = const configPath =
process.argv.length <= 2 ? 'project-config.js' : process.argv[2] process.argv.length <= 2 ? 'project-config.js' : process.argv[2]
const config = JSON.parse( const config = JSON.parse(
fs.readFileSync(path.join('config', configPath), 'utf8'), fs.readFileSync(path.join('config', configPath), 'utf8')
) )
config.port = (process.env.PORT || config.port || 7777) as number config.port = (process.env.PORT || config.port || 7777) as number

View file

@ -4,7 +4,8 @@ import type { Config } from 'src/types/config'
const build = async (config: Config): Promise<KeyGenerator> => { const build = async (config: Config): Promise<KeyGenerator> => {
const pwOptions = config.keyGenerator const pwOptions = config.keyGenerator
pwOptions.type = pwOptions.type || 'random' pwOptions.type = pwOptions.type || 'random'
const Generator = (await import(`../key-generators/${pwOptions.type}`)).default const Generator = (await import(`../key-generators/${pwOptions.type}`))
.default
const keyGenerator = new Generator(pwOptions) const keyGenerator = new Generator(pwOptions)
return keyGenerator return keyGenerator

View file

@ -11,7 +11,7 @@ import DocumentHandler from 'src/lib/document-handler'
import buildDocumenthandler from 'src/lib/document-handler/builder' import buildDocumenthandler from 'src/lib/document-handler/builder'
import { import {
getStaticDirectory, getStaticDirectory,
getStaticItemDirectory, getStaticItemDirectory
} from 'src/lib/helpers/directory' } from 'src/lib/helpers/directory'
const config: Config = getConfig() const config: Config = getConfig()
@ -33,17 +33,17 @@ buildDocumenthandler(config)
) { ) {
const dest = `${item.substring( const dest = `${item.substring(
0, 0,
item.length - 3, item.length - 3
)}.min${item.substring(item.length - 3)}` )}.min${item.substring(item.length - 3)}`
const origCode = fs.readFileSync( const origCode = fs.readFileSync(
getStaticItemDirectory(__dirname, item), getStaticItemDirectory(__dirname, item),
'utf8', 'utf8'
) )
fs.writeFileSync( fs.writeFileSync(
getStaticItemDirectory(__dirname, dest), getStaticItemDirectory(__dirname, dest),
uglify.minify(origCode).code, uglify.minify(origCode).code,
'utf8', 'utf8'
) )
winston.info(`compressed ${item} into ${dest}`) winston.info(`compressed ${item} into ${dest}`)
} }
@ -66,12 +66,12 @@ buildDocumenthandler(config)
cb => { cb => {
winston.debug('loaded static document', { success: cb }) winston.debug('loaded static document', { success: cb })
}, },
true, true
) )
} else { } else {
winston.warn('failed to load static document', { winston.warn('failed to load static document', {
name, name,
path: documentPath, path: documentPath
}) })
} }
}) })
@ -86,25 +86,25 @@ buildDocumenthandler(config)
// get raw documents - support getting with extension // get raw documents - support getting with extension
app.get('/raw/:id', async (request, response) => app.get('/raw/:id', async (request, response) =>
documentHandler.handleRawGet(request, response), documentHandler.handleRawGet(request, response)
) )
app.head('/raw/:id', (request, response) => app.head('/raw/:id', (request, response) =>
documentHandler.handleRawGet(request, response), documentHandler.handleRawGet(request, response)
) )
// // add documents // // add documents
app.post('/documents', (request, response) => app.post('/documents', (request, response) =>
documentHandler.handlePost(request, response), documentHandler.handlePost(request, response)
) )
// get documents // get documents
app.get('/documents/:id', (request, response) => app.get('/documents/:id', (request, response) =>
documentHandler.handleGet(request, response), documentHandler.handleGet(request, response)
) )
app.head('/documents/:id', (request, response) => app.head('/documents/:id', (request, response) =>
documentHandler.handleGet(request, response), documentHandler.handleGet(request, response)
) )
// Otherwise, try to match static files // Otherwise, try to match static files
@ -113,8 +113,8 @@ buildDocumenthandler(config)
path: getStaticDirectory(__dirname), path: getStaticDirectory(__dirname),
content: { maxAge: config.staticMaxAge }, content: { maxAge: config.staticMaxAge },
passthrough: true, passthrough: true,
index: false, index: false
}), })
) )
// Then we can loop back - and everything else should be a token, // Then we can loop back - and everything else should be a token,
@ -129,8 +129,8 @@ buildDocumenthandler(config)
connectSt({ connectSt({
path: getStaticDirectory(__dirname), path: getStaticDirectory(__dirname),
content: { maxAge: config.staticMaxAge }, content: { maxAge: config.staticMaxAge },
index: 'index.html', index: 'index.html'
}), })
) )
app.listen(config.port, config.host, () => { app.listen(config.port, config.host, () => {

View file

@ -78,4 +78,3 @@ export interface KeyGeneratorConfig {
keyspace?: string keyspace?: string
path?: string path?: string
} }

View file

@ -1,11 +1,11 @@
export interface Logging { export interface Logging {
level: string level: string
type: type:
| 'File' | 'File'
| 'Console' | 'Console'
| 'Loggly' | 'Loggly'
| 'DailyRotateFile' | 'DailyRotateFile'
| 'Http' | 'Http'
| 'Memory' | 'Memory'
| 'Webhook' | 'Webhook'
} }

View file

@ -8,6 +8,6 @@ export interface Store {
key: string, key: string,
data: string, data: string,
callback: Callback, callback: Callback,
skipExpire?: boolean, skipExpire?: boolean
) => void ) => void
} }