Last active
December 3, 2022 23:49
-
-
Save vanishdark/884c3a01bab6e5c4e4e52611b40a68de to your computer and use it in GitHub Desktop.
[Nativescript]-How to upload an Image to AWS S3 pre-assign url with background-http
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Packages need it | |
- Nativescript ofc | |
- Background Http (https://github.com/NativeScript/plugins/tree/main/packages/background-http) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* AWS Parameters Interface | |
*/ | |
export interface AWSParams { | |
name: string; | |
filename: string; | |
mimeType: string; | |
} | |
/** | |
* @category Services | |
*/ | |
export class AmazonWebService extends HttpService { | |
/** | |
* Getter and Setter session | |
* @param {Session} value | |
* @return {Session} | |
*/ | |
public get session(): Session { | |
return this._session; | |
} | |
public set session(value: Session) { | |
this._session = value; | |
} | |
private _session: Session; | |
constructor() { | |
this.session = this.initSession(); | |
} | |
// this.post is a extension from the HTTPService | |
async requestUrl(name: string): Promise<HttpResponse> { | |
return this.post( | |
url, // The api url to get the pre-assign url for AWS | |
{ filename: name }, | |
{ | |
Authorization: `Bearer ${AuthenticationService.credentials?.accessToken}`, | |
}, | |
); | |
} | |
async sendImage(url: string, file: any, name?: string, type?: string): Promise<string> { | |
try { | |
if (!type) type = 'image/jpg'; | |
if (!name) name = 'filename.jpg'; | |
const request: Request = { | |
url, | |
method: 'PUT', | |
headers: { | |
'Content-Type': type, | |
reportProgress: true, | |
}, | |
description: 'UpladingFile' + file, | |
}; | |
this.initTask(file, request, name, type); | |
return url; | |
} catch (e) { | |
console.log(e); | |
return ''; | |
} | |
} | |
/** | |
*Initialize the session | |
*/ | |
initSession(): Session { | |
return bghttp.session('image-upload'); | |
} | |
/** | |
* Initialize the task from session | |
*/ | |
initTask(file: any, request: Request, name?: string, type?: string): void { | |
try { | |
const task = this.session.uploadFile(file, request); | |
task.on('progress', e => console.log('progress', e.currentBytes)); | |
task.on('responded', e => console.log('responded', e.responseCode)); | |
task.on('error', e => console.log('error', e.responseCode)); | |
task.on('complete', e => console.log('complete', e)); | |
} catch (e) { | |
console.log('initTaks Erro -', e); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//Example how to use the service (I will update later with a new structure) | |
const value = new ImageSource(); // just to give context of what is the value; | |
export const uploadImage = async (value: ImageSource) => { | |
const amazonService = new AmazonService(); | |
const request = await amazonService.requestUrl('filename.png') | |
const preAssignedUrl = request.content?.toJSON().data.url; | |
value.saveToFile(`${knownFolders.documents().path}/filename.png`, 'png'); | |
const file = File.fromPath(`${knownFolders.documents().path}/filename.png`); | |
await amazonService.sendImage(url, | |
`${knownFolders.temp().path}/filename.png`, | |
'filename.png', | |
'image/png') | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export interface Headers { | |
[prop: string]: string; | |
} | |
export enum RequestMethod { | |
GET = 'GET', | |
POST = 'POST', | |
PATCH = 'PATCH', | |
PUT = 'PUT', | |
DELETE = 'DELETE', | |
} | |
/** | |
* @category Services | |
*/ | |
export class HttpService { | |
apiUrl: string; | |
constructor(apiUrl: string | undefined) { | |
if (apiUrl) this.apiUrl = apiUrl; | |
else this.apiUrl = 'localhost:9000'; | |
} | |
async request(method: string, url: string, content: object, headers?: Headers) { | |
const request: HttpRequestOptions = { | |
url, | |
method, | |
}; | |
if (typeof headers !== 'undefined') { | |
request.headers = headers; | |
} | |
if (method !== RequestMethod.GET && method !== RequestMethod.DELETE) { | |
request.content = JSON.stringify(content); | |
} | |
return Http.request(request); | |
} | |
async get(url: string, headers?: Headers): Promise<HttpResponse> { | |
if (typeof headers !== 'undefined') { | |
const request = Http.request({ | |
url: this.apiUrl + url, | |
headers, | |
method: 'GET', | |
}); | |
console.log('GET REQUEST - ' + url, await request); | |
return request; | |
} | |
const request = Http.request({ | |
url: this.apiUrl + url, | |
method: 'GET', | |
}); | |
console.log('GET REQUEST - ' + url, await request); | |
return request; | |
} | |
async post(url: string, body: object, headers: Headers): Promise<HttpResponse> { | |
console.log(this.apiUrl + url); | |
const request = Http.request({ | |
url: this.apiUrl + url, | |
method: 'POST', | |
headers: { | |
Authorization: headers.Authorization, | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
}, | |
content: JSON.stringify(body), | |
}); | |
console.log('POST REQUEST - ' + url, await request); | |
return request; | |
} | |
async patch(url: string, body: object, headers: Headers): Promise<HttpResponse> { | |
const request = Http.request({ | |
url: this.apiUrl + url, | |
method: 'PATCH', | |
headers: { | |
Authorization: headers.Authorization, | |
Accept: 'application/json', | |
'Content-Type': 'application/json', | |
}, | |
content: JSON.stringify(body), | |
}); | |
console.log('PATCH REQUEST - ' + url, await request); | |
return request; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment