Skip to content

Commit

Permalink
feat: upload assets (#685)
Browse files Browse the repository at this point in the history
* feat: upload assets

* chore: remove console.log
  • Loading branch information
cazala committed Jul 31, 2023
1 parent 0616ad1 commit 5c25f76
Showing 1 changed file with 47 additions and 0 deletions.
47 changes: 47 additions & 0 deletions src/S3/S3Router.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
import { Request, Response } from 'express'
import fetch from 'node-fetch'
import { hashV1 } from '@dcl/hashing'
import { server } from 'decentraland-server'

import { Router } from '../common/Router'
Expand All @@ -7,6 +9,8 @@ import { getBucketURL } from './s3'
import { S3AssetPack } from './S3AssetPack'
import { S3Content } from './S3Content'
import { S3Model } from './S3Model'
import { withAuthentication } from '../middleware'
import { getUploader } from './uploads'

export class S3Router extends Router {
mount() {
Expand All @@ -24,6 +28,29 @@ export class S3Router extends Router {
* Get the response headers for a file
*/
this.router.head('/storage/contents/:filename', this.handleContents)

/**
* Return whether a file exists or not in the content server without downloading it
*/
this.router.get(
'/storage/contents/:filename/exists',
server.handleRequest(this.handleExists)
)

/**
* Upload a file
*/
this.router.post(
'/storage/upload',
withAuthentication,
getUploader({
getFileStreamKey: async (file) => {
const hash = await hashV1(file.stream)
return new S3Content().getFileKey(hash)
},
}).any(),
server.handleRequest(this.handleUpload)
)
}

private buildRedirectUrl(
Expand Down Expand Up @@ -53,4 +80,24 @@ export class S3Router extends Router {
const model = new S3Content()
this.permanentlyRedirectFile(req, res, model)
}

private handleExists = async (req: Request, res: Response) => {
const model = new S3Content()
const filename = server.extractFromReq(req, 'filename')
const ts = req.query.ts as string
const url = this.buildRedirectUrl(model, filename, ts)
try {
const content = await fetch(url)
if (content.ok) {
return // it exists
}
} catch (error) {}
res.status(404) // it does not exist
}

private handleUpload(req: Request, _res: Response) {
return {
hash: (req.files as { fieldname: string }[])[0]!.fieldname.split('/')[1],
}
}
}

0 comments on commit 5c25f76

Please sign in to comment.