Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Commit 0fc8004

Browse filesBrowse files
authored
Merge pull request #128 from albertcito/feature/127-upload-image
Feature/127 upload image
2 parents cb57aa4 + ce8a280 commit 0fc8004
Copy full SHA for 0fc8004

File tree

23 files changed

+677
-73
lines changed
Filter options

23 files changed

+677
-73
lines changed

‎README.md

Copy file name to clipboardExpand all lines: README.md
+1-1Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@
1212
- Create .env file `cp .env.example .env`
1313
- Run `yarn install` (Installs all the dependencies for your project)
1414
- Run postgress: `postgres -D /usr/local/var/postgres`
15-
- You can also run the database in docker with `docker-compose up`
15+
- You can also run the database in docker with `docker-compose up`
1616
- Run `yarn typeorm migration:run` (Creates all of the database tables)
1717

1818
## Faker Data

‎package.json

Copy file name to clipboardExpand all lines: package.json
+5-2Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
"description": "",
55
"main": "index.js",
66
"scripts": {
7-
"build": "rm -rf build/ && tsc && tscpaths -p tsconfig.json -s ./src -o ./build && cp -R src/resources build/resources",
7+
"build": "rm -rf build/ && tsc && tscpaths -p tsconfig.json -s ./src -o ./build && cp -R src/resources build/resources && cp -R src/tests/files build/tests/files",
88
"dev": "nodemon --exec ts-node -r tsconfig-paths/register src/index.ts",
99
"test": "jest --config ./jest.dev.config.js --roots src/tests",
1010
"eslint": "eslint --ext=jsx,ts,tsx 'src/**/*.{ts,tsx}'",
@@ -29,6 +29,7 @@
2929
"@types/multer": "^1.4.4",
3030
"@types/node": "^14.11.2",
3131
"@types/nodemailer": "^6.4.0",
32+
"@types/sharp": "^0.27.1",
3233
"@types/supertest": "^2.0.10",
3334
"@types/uuid": "^8.3.0",
3435
"@types/validatorjs": "^3.15.0",
@@ -53,7 +54,6 @@
5354
"apollo-server-express": "^2.18.1",
5455
"apollo-server-plugin-base": "^0.10.1",
5556
"argon2": "^0.27.0",
56-
"body-parser": "^1.19.0",
5757
"class-transformer": "^0.3.1",
5858
"class-validator": "^0.12.2",
5959
"cors": "^2.8.5",
@@ -62,13 +62,16 @@
6262
"express": "^4.17.1",
6363
"express-session": "^1.17.1",
6464
"faker": "^5.1.0",
65+
"file-type": "^16.2.0",
6566
"graphql": "^15.3.0",
67+
"graphql-upload": "^11.0.0",
6668
"i18n": "^0.13.2",
6769
"nodemailer": "^6.4.14",
6870
"nodemon": "^2.0.4",
6971
"pg": "^8.5.1",
7072
"reflect-metadata": "^0.1.13",
7173
"routing-controllers": "^0.9.0-alpha.6",
74+
"sharp": "^0.27.0",
7275
"ts-node": "^9.0.0",
7376
"type-graphql": "^1.0.0",
7477
"typeorm": "^0.2.27",

‎src/config/index.ts

Copy file name to clipboardExpand all lines: src/config/index.ts
+2Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import dotenv from 'dotenv';
22

33
dotenv.config();
44

5+
export const appURL = process.env.APP_URL;
6+
57
export const frontend = {
68
URL: {
79
activeEmail: `${process.env.FRONTEND_URL}/active-email?token=%s`,

‎src/db/entities/Media/Image.ts

Copy file name to clipboard
+56Lines changed: 56 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import {
2+
Field, ObjectType, Int,
3+
} from 'type-graphql';
4+
import {
5+
Entity, PrimaryGeneratedColumn, Column,
6+
} from 'typeorm';
7+
8+
import { appURL } from 'src/config';
9+
import BaseEntity from '../BaseEntity';
10+
11+
@ObjectType()
12+
@Entity({ name: 'image', schema: 'media' })
13+
export default class Image extends BaseEntity {
14+
@Field(() => Int)
15+
@PrimaryGeneratedColumn()
16+
id: number;
17+
18+
@Field(() => Int, { nullable: true })
19+
@Column({ name: 'title_id' })
20+
titleID?: number;
21+
22+
@Field(() => String)
23+
@Column()
24+
name: string;
25+
26+
@Column()
27+
path: string;
28+
29+
url() {
30+
return `${appURL}/${this.path}/${this.fileName()}`;
31+
}
32+
33+
fileName() {
34+
return `${this.id}.${this.ext}`;
35+
}
36+
37+
@Field(() => String)
38+
@Column()
39+
ext: string;
40+
41+
@Field(() => String)
42+
@Column()
43+
mime?: string;
44+
45+
@Field(() => Int)
46+
@Column()
47+
size?: number;
48+
49+
@Field(() => Int)
50+
@Column()
51+
width?: number;
52+
53+
@Field(() => Int)
54+
@Column()
55+
height?: number;
56+
}
+73Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,73 @@
1+
import {
2+
MigrationInterface, QueryRunner, Table, TableForeignKey,
3+
} from 'typeorm';
4+
5+
import columns from './BaseTableColumns/columns';
6+
7+
export default class Image1601940113477 implements MigrationInterface {
8+
private readonly tableName = 'media.image';
9+
10+
public async up(queryRunner: QueryRunner): Promise<void> {
11+
await queryRunner.manager.query('CREATE SCHEMA IF NOT EXISTS media;');
12+
await queryRunner.createTable(new Table({
13+
name: this.tableName,
14+
columns: [
15+
{
16+
name: 'id',
17+
type: 'integer',
18+
isPrimary: true,
19+
isGenerated: true,
20+
generationStrategy: 'increment',
21+
},
22+
{
23+
name: 'title_id',
24+
type: 'integer',
25+
isNullable: true,
26+
},
27+
{
28+
name: 'name',
29+
type: 'varchar',
30+
},
31+
{
32+
name: 'path',
33+
type: 'varchar',
34+
},
35+
{
36+
name: 'ext',
37+
type: 'varchar',
38+
length: '4',
39+
},
40+
{
41+
name: 'mime',
42+
type: 'varchar',
43+
length: '25',
44+
},
45+
{
46+
name: 'size',
47+
type: 'integer',
48+
},
49+
{
50+
name: 'width',
51+
type: 'integer',
52+
},
53+
{
54+
name: 'height',
55+
type: 'integer',
56+
},
57+
...columns,
58+
],
59+
}), true);
60+
61+
await queryRunner.createForeignKey(this.tableName, new TableForeignKey({
62+
name: 'image_title_translation',
63+
columnNames: ['title_id'],
64+
referencedColumnNames: ['id'],
65+
referencedTableName: 'lang.translation',
66+
onDelete: 'RESTRICT',
67+
}));
68+
}
69+
70+
public async down(queryRunner: QueryRunner): Promise<void> {
71+
await queryRunner.dropTable(this.tableName);
72+
}
73+
}
+21Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import {
2+
Resolver, Mutation, Arg,
3+
} from 'type-graphql';
4+
import { GraphQLUpload, FileUpload } from 'graphql-upload';
5+
6+
import Image from 'src/db/entities/Media/Image';
7+
import ImageUpload from 'src/logic/media/ImageUpload';
8+
import imagesAllowed from 'src/logic/media/imagesAllowed';
9+
10+
@Resolver()
11+
export default class UploadImageResolver {
12+
@Mutation(() => Image)
13+
async imageUpload(
14+
@Arg(
15+
'file', () => GraphQLUpload,
16+
{ description: `Images allowed ${imagesAllowed.join(', ')}` },
17+
) file: FileUpload,
18+
): Promise<Image> {
19+
return (new ImageUpload(file)).upload();
20+
}
21+
}

‎src/index.ts

Copy file name to clipboardExpand all lines: src/index.ts
+2-2Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import connectionOptions from './init/db/connectionOptions';
55

66
const port = process.env.PORT ?? 5000;
77
const main = async () => {
8-
const db = await createConnection(connectionOptions);
9-
const server = await getServer(db);
8+
await createConnection(connectionOptions);
9+
const server = await getServer();
1010
server.listen(port, () => {
1111
// eslint-disable-next-line no-console
1212
console.info(`Server started at localhost:${port}`);

‎src/init/graphql/ApolloServerContext.ts

Copy file name to clipboardExpand all lines: src/init/graphql/ApolloServerContext.ts
-8Lines changed: 0 additions & 8 deletions
This file was deleted.

‎src/init/graphql/public/errorHandlePlugin.ts renamed to ‎src/init/graphql/errorHandlePlugin.ts

Copy file name to clipboardExpand all lines: src/init/graphql/errorHandlePlugin.ts
+3-3Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,17 +1,17 @@
11
import { ApolloServerPlugin, GraphQLRequestContextWillSendResponse } from 'apollo-server-plugin-base';
22
import { HttpQueryError } from 'apollo-server-core';
3+
import { ExpressContext } from 'apollo-server-express/dist/ApolloServer';
34

45
import HttpStatusError from 'src/util/exceptions/HttpStatusError';
56
import isValidException from 'src/util/exceptions/isValidException';
6-
import { ApolloServerContext } from '../ApolloServerContext';
7-
import notify from '../../bugsnag/notify';
7+
import notify from '../bugsnag/notify';
88

99
// I tried to do it like the Apollo test, but its doesn't works
1010
// https://github.com/apollographql/apollo-server/blob/1af2792ed9e18f2bf218a29c2f4f128b6588f9ca/packages/apollo-server-integration-testsuite/src/ApolloServer.ts#L661
1111
const ErrorHandlePlugin: ApolloServerPlugin = {
1212
requestDidStart() {
1313
return {
14-
willSendResponse(requestContext: GraphQLRequestContextWillSendResponse<ApolloServerContext>) {
14+
willSendResponse(requestContext: GraphQLRequestContextWillSendResponse<ExpressContext>) {
1515
const errors = requestContext.errors ?? [];
1616
// eslint-disable-next-line no-restricted-syntax
1717
for (const error of errors) {

‎src/init/graphql/public/server.ts

Copy file name to clipboardExpand all lines: src/init/graphql/public/server.ts
-36Lines changed: 0 additions & 36 deletions
This file was deleted.

‎src/init/graphql/server.ts

Copy file name to clipboard
+28Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import 'reflect-metadata';
2+
import { join } from 'path';
3+
import { BuildSchemaOptions, buildSchema } from 'type-graphql';
4+
import { ApolloServer } from 'apollo-server-express';
5+
6+
import formatError from './formatError';
7+
import ErrorHandlePlugin from './errorHandlePlugin';
8+
9+
export const path = '/graphql';
10+
const server = async () => {
11+
const resolvers = join(__dirname, '../../graphql/resolvers/**/*{.ts,.js}');
12+
const apolloSchemeOptions: BuildSchemaOptions = {
13+
resolvers: [resolvers],
14+
validate: false,
15+
};
16+
const apolloSchema = await buildSchema(apolloSchemeOptions);
17+
return new ApolloServer({
18+
schema: apolloSchema,
19+
context: (context) => context,
20+
formatError,
21+
plugins: [ErrorHandlePlugin],
22+
playground: true,
23+
introspection: true,
24+
uploads: false,
25+
});
26+
};
27+
28+
export default server;

‎src/init/server.ts

Copy file name to clipboardExpand all lines: src/init/server.ts
+12-5Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,16 +4,17 @@ import dotenv from 'dotenv';
44
import Bugsnag from '@bugsnag/js';
55
import { join } from 'path';
66
import i18n from 'i18n';
7-
import { Connection } from 'typeorm';
7+
import { graphqlUploadExpress } from 'graphql-upload';
88

99
import './i18n/index';
1010
import './bugsnag';
1111
import '../util/validatorjs/rules';
1212
import handleErrors from './handleErrors';
13-
import apolloServer from './graphql/public/server';
13+
import ApolloServer, { path } from './graphql/server';
1414
import useControllersApi from './controllers';
15+
import { cors } from 'src/config';
1516

16-
const getApp = async (db: Connection): Promise<Express> => {
17+
const getApp = async (): Promise<Express> => {
1718
dotenv.config();
1819
const app = express();
1920
const middleware = Bugsnag.getPlugin('express');
@@ -26,8 +27,14 @@ const getApp = async (db: Connection): Promise<Express> => {
2627
app.use('/public', express.static(join(__dirname, '../../public')));
2728
// use multi languages
2829
app.use(i18n.init);
29-
// Apollo graphQL
30-
await apolloServer(app, db);
30+
// Apollo graphQL config
31+
app.use(graphqlUploadExpress({ maxFileSize: 10000000, maxFiles: 10 }));
32+
(await ApolloServer()).applyMiddleware({
33+
cors,
34+
app,
35+
path,
36+
bodyParserConfig: true,
37+
});
3138
// Api
3239
useControllersApi(app);
3340
// handle global errors

0 commit comments

Comments
0 (0)
Morty Proxy This is a proxified and sanitized view of the page, visit original site.