Skip to content

Commit

Permalink
chore: refactor: rename Sidecar -> ResponseMeta
Browse files Browse the repository at this point in the history
  • Loading branch information
nytamin committed Jul 3, 2024
1 parent 92e496e commit 73259d9
Show file tree
Hide file tree
Showing 3 changed files with 47 additions and 48 deletions.
20 changes: 11 additions & 9 deletions apps/http-server/packages/generic/src/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import cors from '@koa/cors'
import bodyParser from 'koa-bodyparser'

import { HTTPServerConfig, LoggerInstance, stringifyError, first } from '@sofie-package-manager/api'
import { BadResponse, PackageInfo, Sidecar, Storage, isBadResponse } from './storage/storage'
import { BadResponse, PackageInfo, ResponseMeta, Storage, isBadResponse } from './storage/storage'
import { FileStorage } from './storage/fileStorage'
import { CTX, valueOrFirst } from './lib'
import { parseFormData } from 'pechkin'
Expand Down Expand Up @@ -167,20 +167,22 @@ export class PackageProxyServer {
}
})
}
private async handleStorage(ctx: CTX, storageFcn: () => Promise<{ sidecar: Sidecar; body?: any } | BadResponse>) {
private async handleStorage(ctx: CTX, storageFcn: () => Promise<{ meta: ResponseMeta; body?: any } | BadResponse>) {
try {
const result = await storageFcn()
if (isBadResponse(result)) {
ctx.response.status = result.code
ctx.body = result.reason
} else {
ctx.response.status = result.sidecar.statusCode
if (result.sidecar.type !== undefined) ctx.type = result.sidecar.type
if (result.sidecar.length !== undefined) ctx.length = result.sidecar.length
if (result.sidecar.lastModified !== undefined) ctx.lastModified = result.sidecar.lastModified

for (const [key, value] of Object.entries<string>(result.sidecar.headers)) {
ctx.set(key, value)
ctx.response.status = result.meta.statusCode
if (result.meta.type !== undefined) ctx.type = result.meta.type
if (result.meta.length !== undefined) ctx.length = result.meta.length
if (result.meta.lastModified !== undefined) ctx.lastModified = result.meta.lastModified

if (result.meta.headers) {
for (const [key, value] of Object.entries<string>(result.meta.headers)) {
ctx.set(key, value)
}
}

if (result.body) ctx.body = result.body
Expand Down
61 changes: 29 additions & 32 deletions apps/http-server/packages/generic/src/storage/fileStorage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import mime from 'mime-types'
import prettyBytes from 'pretty-bytes'
import { asyncPipe, CTXPost } from '../lib'
import { HTTPServerConfig, LoggerInstance } from '@sofie-package-manager/api'
import { BadResponse, PackageInfo, Sidecar, Storage } from './storage'
import { BadResponse, PackageInfo, ResponseMeta, Storage } from './storage'
import { Readable } from 'stream'

// Note: Explicit types here, due to that for some strange reason, promisify wont pass through the correct typings.
Expand Down Expand Up @@ -46,7 +46,7 @@ export class FileStorage extends Storage {
await fsMkDir(this._basePath, { recursive: true })
}

async listPackages(): Promise<{ sidecar: Sidecar; body: { packages: PackageInfo[] } } | BadResponse> {
async listPackages(): Promise<{ meta: ResponseMeta; body: { packages: PackageInfo[] } } | BadResponse> {
const packages: PackageInfo[] = []

const getAllFiles = async (basePath: string, dirPath: string) => {
Expand Down Expand Up @@ -79,12 +79,11 @@ export class FileStorage extends Storage {
return 0
})

const sidecar: Sidecar = {
const meta: ResponseMeta = {
statusCode: 200,
headers: {},
}

return { sidecar, body: { packages } }
return { meta, body: { packages } }
}
private async getFileInfo(paramPath: string): Promise<
| {
Expand Down Expand Up @@ -116,42 +115,40 @@ export class FileStorage extends Storage {
lastModified: stat.mtime,
}
}
async headPackage(paramPath: string): Promise<{ sidecar: Sidecar } | BadResponse> {
async headPackage(paramPath: string): Promise<{ meta: ResponseMeta } | BadResponse> {
const fileInfo = await this.getFileInfo(paramPath)

if (!fileInfo.found) {
return { code: 404, reason: 'Package not found' }
}

const sidecar: Sidecar = {
const meta: ResponseMeta = {
statusCode: 204,
headers: {},
}
this.updateSideCarWithFileInfo(sidecar, fileInfo)
this.updateMetaWithFileInfo(meta, fileInfo)

return { sidecar }
return { meta }
}
async getPackage(paramPath: string): Promise<{ sidecar: Sidecar; body: any } | BadResponse> {
async getPackage(paramPath: string): Promise<{ meta: ResponseMeta; body: any } | BadResponse> {
const fileInfo = await this.getFileInfo(paramPath)

if (!fileInfo.found) {
return { code: 404, reason: 'Package not found' }
}
const sidecar: Sidecar = {
const meta: ResponseMeta = {
statusCode: 200,
headers: {},
}
this.updateSideCarWithFileInfo(sidecar, fileInfo)
this.updateMetaWithFileInfo(meta, fileInfo)

const readStream = fs.createReadStream(fileInfo.fullPath)

return { sidecar, body: readStream }
return { meta, body: readStream }
}
async postPackage(
paramPath: string,
ctx: CTXPost,
fileStreamOrText: string | Readable | undefined
): Promise<{ sidecar: Sidecar; body: any } | BadResponse> {
): Promise<{ meta: ResponseMeta; body: any } | BadResponse> {
const fullPath = path.join(this._basePath, paramPath)

await fsMkDir(path.dirname(fullPath), { recursive: true })
Expand All @@ -164,28 +161,27 @@ export class FileStorage extends Storage {
plainText = fileStreamOrText
}

const sidecar: Sidecar = {
const meta: ResponseMeta = {
statusCode: 200,
headers: {},
}

if (plainText) {
// store plain text into file
await fsWriteFile(fullPath, plainText)

sidecar.statusCode = 201
return { sidecar, body: { code: 201, message: `${exists ? 'Updated' : 'Inserted'} "${paramPath}"` } }
meta.statusCode = 201
return { meta, body: { code: 201, message: `${exists ? 'Updated' : 'Inserted'} "${paramPath}"` } }
} else if (fileStreamOrText && typeof fileStreamOrText !== 'string') {
const fileStream = fileStreamOrText
await asyncPipe(fileStream, fs.createWriteStream(fullPath))

sidecar.statusCode = 201
return { sidecar, body: { code: 201, message: `${exists ? 'Updated' : 'Inserted'} "${paramPath}"` } }
meta.statusCode = 201
return { meta, body: { code: 201, message: `${exists ? 'Updated' : 'Inserted'} "${paramPath}"` } }
} else {
return { code: 400, reason: 'No files provided' }
}
}
async deletePackage(paramPath: string): Promise<{ sidecar: Sidecar; body: any } | BadResponse> {
async deletePackage(paramPath: string): Promise<{ meta: ResponseMeta; body: any } | BadResponse> {
const fullPath = path.join(this._basePath, paramPath)

if (!(await this.exists(fullPath))) {
Expand All @@ -194,12 +190,11 @@ export class FileStorage extends Storage {

await fsUnlink(fullPath)

const sidecar: Sidecar = {
const meta: ResponseMeta = {
statusCode: 200,
headers: {},
}

return { sidecar, body: { message: `Deleted "${paramPath}"` } }
return { meta, body: { message: `Deleted "${paramPath}"` } }
}

private async exists(fullPath: string) {
Expand Down Expand Up @@ -287,21 +282,23 @@ export class FileStorage extends Storage {
* @param {CTX} ctx
* @memberof FileStorage
*/
private updateSideCarWithFileInfo(sidecar: Sidecar, info: FileInfo): void {
sidecar.type = info.mimeType
sidecar.length = info.length
sidecar.lastModified = info.lastModified
private updateMetaWithFileInfo(meta: ResponseMeta, info: FileInfo): void {
meta.type = info.mimeType
meta.length = info.length
meta.lastModified = info.lastModified

if (!meta.headers) meta.headers = {}

// Check the config. 0 or -1 means it's disabled:
if (this.config.httpServer.cleanFileAge >= 0) {
sidecar.headers['Expires'] = FileStorage.calculateExpiresTimestamp(
meta.headers['Expires'] = FileStorage.calculateExpiresTimestamp(
info.lastModified,
this.config.httpServer.cleanFileAge
)
}
}
/**
* Calculate the expiration timestamp, given a starting Date point and timespan duration
* Calculate the expiration timestamp, given a starting Date point and time-span duration
*
* @private
* @static
Expand Down
14 changes: 7 additions & 7 deletions apps/http-server/packages/generic/src/storage/storage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,21 +6,21 @@ export abstract class Storage {
abstract getInfo(): string
abstract listPackages(): Promise<
| {
sidecar: Sidecar
meta: ResponseMeta
body: {
packages: PackageInfo[]
}
}
| BadResponse
>
abstract headPackage(path: string): Promise<{ sidecar: Sidecar } | BadResponse>
abstract getPackage(path: string): Promise<{ sidecar: Sidecar; body: any } | BadResponse>
abstract headPackage(path: string): Promise<{ meta: ResponseMeta } | BadResponse>
abstract getPackage(path: string): Promise<{ meta: ResponseMeta; body: any } | BadResponse>
abstract postPackage(
path: string,
ctx: CTXPost,
fileStreamOrText: string | Readable | undefined
): Promise<{ sidecar: Sidecar; body: any } | BadResponse>
abstract deletePackage(path: string): Promise<{ sidecar: Sidecar; body: any } | BadResponse>
): Promise<{ meta: ResponseMeta; body: any } | BadResponse>
abstract deletePackage(path: string): Promise<{ meta: ResponseMeta; body: any } | BadResponse>
}
export interface BadResponse {
code: number
Expand All @@ -40,12 +40,12 @@ export type PackageInfo = {
modified: string
}

export interface Sidecar {
export interface ResponseMeta {
statusCode: number
type?: string
length?: number
lastModified?: Date
headers: {
headers?: {
[key: string]: string
}
}

0 comments on commit 73259d9

Please sign in to comment.