Skip to content

Commit

Permalink
feat: add file storage
Browse files Browse the repository at this point in the history
  • Loading branch information
recallwei committed May 29, 2023
1 parent 6bbb3d6 commit 2d82b78
Show file tree
Hide file tree
Showing 15 changed files with 205 additions and 10 deletions.
2 changes: 2 additions & 0 deletions .env
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ DB_HOST=localhost
DB_PORT=5432
DB_NAME=est-db
DB_URL=postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}

FILE_STORAGE_PATH=storage
2 changes: 2 additions & 0 deletions .env.example
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,5 @@ DB_HOST=localhost
DB_PORT=5432
DB_NAME=est-db
DB_URL=postgresql://${DB_USER}:${DB_PASSWORD}@${DB_HOST}:${DB_PORT}/${DB_NAME}

FILE_STORAGE_PATH=storage
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@ pnpm-debug.log*

# Misc
.DS_Store
dist
coverage
*.local

Expand All @@ -31,4 +30,5 @@ coverage
*.sw?
*.zip

temp
/storage
/temp
2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"http-errors": "~2.0.0",
"jsonwebtoken": "^9.0.0",
"morgan": "~1.10.0",
"multer": "1.4.5-lts.1",
"pg": "^8.11.0",
"prisma": "^4.14.1",
"tsconfig-paths": "^4.2.0",
Expand All @@ -59,6 +60,7 @@
"@types/http-errors": "^2.0.1",
"@types/jsonwebtoken": "^9.0.2",
"@types/morgan": "^1.9.4",
"@types/multer": "^1.4.7",
"@types/node": "20.2.3",
"@types/pg": "^8.10.1",
"@types/uuid": "^9.0.1",
Expand Down
97 changes: 96 additions & 1 deletion pnpm-lock.yaml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

14 changes: 13 additions & 1 deletion src/app.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import bodyParser from 'body-parser'
import chalk from 'chalk'
import type { Express, NextFunction, Request, Response } from 'express'
import express from 'express'
import fs from 'fs'
import createError from 'http-errors'
import logger from 'morgan'
import morgan from 'morgan'
import path from 'path'

import routes from '@/routes'

import { GlobalFileStorageConfig } from './shared'

const App: Express = express()

App.use(logger('dev'))
Expand All @@ -18,9 +22,17 @@ App.use(bodyParser.json())
App.use(bodyParser.urlencoded({ extended: true }))

// Static files setup
App.use('/public', express.static(path.join(__dirname, '@/public')))
App.use('/static', express.static(path.join(__dirname, '@/static')))

// Create file storage folder if not exists
const storageFolder = GlobalFileStorageConfig.FILE_STORAGE_PATH
try {
fs.accessSync(storageFolder)
} catch (e) {
fs.mkdirSync(storageFolder, { recursive: true })
console.log(chalk.green('[File Storage] File storage folder created.'))
}

// Init routes
routes.forEach((route) => {
App.use(route.path, route.router)
Expand Down
8 changes: 2 additions & 6 deletions src/prisma/seed.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,18 +12,14 @@ const SEED_USER = 'Admin'

const defaultUser: Prisma.UserCreateInput = {
uuid: generateUUID(),
username: 'BruceSong',
email: '[email protected]',
username: 'Admin',
password: '$2b$10$kZEDiHCgDhFmX7/sKwYm1ORMK99FNk/QQgebcwBflKrAWKGA.D46W',
name: 'Bruce Song',
firstName: 'Bruce',
lastName: 'Song',
name: 'Admin',
gender: Gender.UNDEFINED,
phoneNumber: randPhoneNumber(),
birthDate: randPastDate(),
address: randFullAddress(),
avatarUrl: randAvatar(),
biography: 'I am a Web developer.',
verified: true,
enabled: true,
roles: Array.of(Role.ADMIN),
Expand Down
5 changes: 5 additions & 0 deletions src/routes/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import homeRouter from './home.controller'
import loginRouter from './login.controller'
import settingsRouter from './settings.controller'
import uploadRouter from './upload.controller'
import userRouter from './users.controller'

const routes = [
Expand All @@ -19,6 +20,10 @@ const routes = [
{
path: '/settings',
router: settingsRouter
},
{
path: '/upload',
router: uploadRouter
}
]

Expand Down
43 changes: 43 additions & 0 deletions src/routes/upload.controller.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import type { Request, Response, Router } from 'express'
import express from 'express'
import { readFileSync } from 'fs'

import { UploadService } from '@/services/upload'
import { upload } from '@/shared'
import type { BaseResponse } from '@/types'

const router: Router = express.Router()

router.get('/', (request: Request, response: Response) => {
const file = readFileSync('storage/images/a278294ea9942307a598d89ba88f572a', { encoding: 'utf8' })
console.log(file)
response.set('content-type', 'image/png')
response.status(200).send(file)
})

router.post('/', upload.single('file'), async (request: Request, response: BaseResponse<any>) => {
const { file } = request
if (!file) {
response.status(400).json({
message: 'File is required.'
})
return
}

UploadService.logFileInfo(file)

response.json({
data: file
})
})

router.post('/batch', upload.array('files'), async (request: Request, response: BaseResponse<string>) => {
const { files } = request

console.log(files)
response.json({
data: ''
})
})

export default router
2 changes: 2 additions & 0 deletions src/services/upload/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export * from './upload.models'
export * as UploadService from './upload.services'
6 changes: 6 additions & 0 deletions src/services/upload/upload.models.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
export type UploadFileInfo = {
mimetype: string
originalname: string
size: string
path: string
}
9 changes: 9 additions & 0 deletions src/services/upload/upload.services.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
// export const processUploadFile = async (file: File): Promise<Upload> => {}

export const logFileInfo = (file: Express.Multer.File) => {
const { mimetype, originalname, size, path } = file
console.log('Mime Type: %s', mimetype)
console.log('Original Name: %s', originalname)
console.log('File Size: %s', size)
console.log('File Path: %s', path)
}
Loading

0 comments on commit 2d82b78

Please sign in to comment.