Skip to content

Commit

Permalink
Merge pull request #2 from dabapps/reduxify
Browse files Browse the repository at this point in the history
Reduxify
  • Loading branch information
JakeSidSmith authored Apr 25, 2019
2 parents 0ca2813 + 356c606 commit fc1896f
Show file tree
Hide file tree
Showing 18 changed files with 835 additions and 151 deletions.
2 changes: 1 addition & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
/coverage/*
/build/*
/dist/*
.vscode/*
/.vscode/*

.DS_Store
npm-debug.log*
119 changes: 98 additions & 21 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,11 @@

[![Build Status](https://travis-ci.com/dabapps/django-s3-file-upload-client.svg?token=k7ApnEQbpXLoWVm5Bc9o&branch=master)](https://travis-ci.com/dabapps/django-s3-file-upload-client)

Upload files from the browser to S3 - client side implementation
Upload files from the browser to S3 - client side implementation (with redux integration)

For the server side implementation see [github.com/dabapps/django-s3-file-upload-server](https://github.com/dabapps/django-s3-file-upload-server)

## Getting Started

### Installation
## Installation

To install the package run:

Expand All @@ -18,33 +16,79 @@ npm i @dabapps/django-s3-file-upload -S

## Usage

### How it works

The flow to be able to upload files from the browser straight to AWS is as follows.
![Flow S3 file uploads](images/flow-s3-file-uploads.png)

All you need to do is import and call the function `uploadFileToS3` with your file and it will chain the three requests that the frontend needs to make to upload a file from the browser to S3:
1. request upload from server
2. upload file to AWS S3
3. mark upload as complete on server
This library abstracts away the process of chaining the three requests that the frontend needs to make to upload a file from the browser to S3:
1. Request upload from server
2. Upload file to AWS S3
3. Mark upload as complete on server

The implementation is specific to the endpoints setup in this repo [github.com/dabapps/django-s3-file-upload-server](https://github.com/dabapps/django-s3-file-upload-server) so be sure to have the backend configured accordingly.

### Redux integration

This library provides 3 functions that can be combined to handle uploading multiple files, and storing the results, errors, and loading states in redux.

The function `uploadFileToS3` returns a `Promise` of type `Promise<UploadData>` with:
#### createActionSet

This function simply creates an object with some keys that will be used internally to allow the action and reducer to communicate.

```ts
interface UploadData {
id: string;
created: string;
modified: string;
complete_url: string;
file: string;
file_key: string;
file_path: string;
filename: string;
upload_form: UploadForm;
const UPLOAD_PROFILE_PHOTO = createActionSet('UPLOAD_PROFILE_PHOTO');
```

#### createFileUploadAction

This creates a [redux-thunk](https://github.com/reduxjs/redux-thunk) action that handles dispatching requests, and actions that track the loading states of the files, as well as the responses / errors.

```ts
const uploadProfilePhoto = createFileUploadAction(UPLOAD_PROFILE_PHOTO);
```

`createFileUploadAction` takes an action set, and an optional options object, and returns a `Promise<UploadData>` (see [Types](#types)).

Actions created with this function will not throw errors by default. This means that calling `.catch` on the returned promise will not be effective unless you utilize the following option...

Currently the options object only exists to allow you to provide a `shouldRethrow` function, which is called with any errors, and will cause the action to rethrow any errors if `true` is returned from `shouldRethrow`.

Once you've created your action you can then dispatch this from your store, or connected component e.g.

```ts
class MyComponent extends PureComponent<Props> {
// ...
private onSubmit = (data: FormData) => {
this.props.uploadProfilePhoto([data.picture]);
}
// ...
}

export default connect(undefined, { uploadProfilePhoto })(MyComponent);
```

The implementation is specific to the endpoints setup in this repo [github.com/dabapps/django-s3-file-upload-server](https://github.com/dabapps/django-s3-file-upload-server) so be sure to have the backend configured accordingly.
This takes an array of files. If you only have a single file to upload just provide an array containing that file.

## Examples
You should prevent the user from attempting to upload the same set of, or additional files while the requests are in progress (as this will cause issues with the loading states). You can check the current loading state from the [reducer](#createFileUploadReducer), and disable your submit button.

#### createFileUploadReducer

This function is used to create a reducer for a specific set of file uploads.

DO NOT use the same reducer for uploading multiple sets of files unless you really know what you are doing.

```ts
const profilePhotoUpload = createFileUploadReducer(UPLOAD_PROFILE_PHOTO);
```

This can then be added to your store, and connected to React components to provide you with the `UploadState` (see [Types](#types)).

### Basic usage

The function `uploadFileToS3` is used internally by the other functions that integrate with redux. If you're not using redux, you can use this to upload individual files, and manually store the loading state, responses, and errors.

`uploadFileToS3` returns a `Promise` of type `Promise<UploadData>` (see [Types](#types)).

Let's say we have a form which contains a `file`, which we want to upload to S3 on submit, we can do the following:

Expand Down Expand Up @@ -88,6 +132,39 @@ const handleSubmit = (formData: FormData) => {
};
```

### Types

The response type for each file upload:

```ts
interface UploadData {
id: string;
created: string;
modified: string;
complete_url: string;
file: string;
file_key: string;
file_path: string;
filename: string;
upload_form: UploadForm;
}
```

Reducer state:

```ts
interface UploadState {
loading: boolean;
fileCount: number; // Total number of files to be uploaded
inFlightCount: number; // Number of files being uploaded (but have not finished)
completeCount: number;
successCount: number;
failureCount: number;
data: undefined | ReadonlyArray<UploadData>;
error: undefined | ReadonlyArray<unknown>;
}
```

## Code of conduct

For guidelines regarding the code of conduct when contributing to this repository please review [https://www.dabapps.com/open-source/code-of-conduct/](https://www.dabapps.com/open-source/code-of-conduct/)
39 changes: 36 additions & 3 deletions package-lock.json

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

9 changes: 7 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,11 +9,12 @@
},
"scripts": {
"dist": "rm -rf dist/ && mkdir -p dist/ && tsc --project './tsconfig.dist.json'",
"typecheck": "tsc --noEmit --project tsconfig.json",
"lint": "tsc --noEmit --project tsconfig.json && npm run prettier-check && tslint --project tsconfig.json '{src,tests,types,examples,docs}/**/*.@(ts|tsx)'",
"prettier-check": "prettier --check '**/*.{ts,tsx,js,jsx}'",
"prettier": "prettier --write '**/*.{ts,tsx,js,jsx}'",
"tests": "jest",
"test": "npm run lint && npm run tests -- --runInBand --coverage"
"test": "npm run lint && npm run typecheck && npm run tests -- --runInBand --coverage"
},
"repository": {
"type": "git",
Expand All @@ -35,8 +36,12 @@
},
"homepage": "https://github.com/dabapps/django-s3-file-upload-client#readme",
"dependencies": {
"@dabapps/redux-create-reducer": "^1.0.3",
"@types/redux-thunk": "^2.1.0",
"axios": "^0.18.0",
"js-cookie": "^2.2.0"
"js-cookie": "^2.2.0",
"redux": "*",
"redux-thunk": "*"
},
"devDependencies": {
"@types/jest": "^24.0.9",
Expand Down
50 changes: 50 additions & 0 deletions src/actions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import { AnyAction } from 'redux';
import { ThunkDispatch } from 'redux-thunk';
import {
ActionSet,
BeginAction,
FailureAction,
FileUploadOptions,
SuccessAction,
} from './types';
import { uploadFileToS3 } from './upload-file-to-s3';

export const uploadFileWithLoading = <S>(
actionSet: ActionSet,
file: File,
dispatch: ThunkDispatch<S, unknown, AnyAction>
) => {
dispatch({ type: actionSet.REQUEST });

return uploadFileToS3(file)
.then(data => {
dispatch<SuccessAction>({ type: actionSet.SUCCESS, payload: data });
return data;
})
.catch(error => {
dispatch<FailureAction>({ type: actionSet.FAILURE, payload: error });
throw error;
});
};

export const createFileUploadAction = <S>(
actionSet: ActionSet,
options?: FileUploadOptions
) => (files: ReadonlyArray<File>) => (
dispatch: ThunkDispatch<S, unknown, AnyAction>
) => {
dispatch<BeginAction>({
type: actionSet.BEGIN,
payload: files.length,
});

const promises = files.map(file =>
uploadFileWithLoading(actionSet, file, dispatch)
);

return Promise.all(promises).catch(error => {
if (options && options.shouldRethrow && options.shouldRethrow(error)) {
throw error;
}
});
};
14 changes: 14 additions & 0 deletions src/constants.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
import { UploadState } from './types';

export const POST = 'POST';

export const INITIAL_REDUCER_STATE: UploadState = {
loading: false,
fileCount: 0,
inFlightCount: 0,
completeCount: 0,
successCount: 0,
failureCount: 0,
data: undefined,
error: undefined,
};
Loading

0 comments on commit fc1896f

Please sign in to comment.