How to use createPresignedURL method in chromeless

Best JavaScript code snippet using chromeless

wip.js

Source:wip.js Github

copy

Full Screen

1const { net } = require('electron');2const logger = require('./logger');3const FormData = require('form-data');4const fs = require('fs');5const { GraphQLClient } = require('graphql-request');6const store = require('./store');7let devMode = false;8let apiKey;9let clientId;10function client() {11 const endpoint = devMode12 ? 'http://wip.test:5000/graphql'13 : 'https://wip.co/graphql';14 return new GraphQLClient(endpoint, {15 headers: {16 authorization: `Bearer ${apiKey}`,17 },18 });19}20function setDevMode(value) {21 devMode = value;22}23function getDevMode() {24 return devMode;25}26function setApiKey(value) {27 apiKey = value;28}29function setClientId(value) {30 clientId = value;31}32function getOAuthURL() {33 var base = devMode ? 'http://wip.test:5000' : 'https://wip.co';34 return `${base}/oauth/authorize?client_id=${clientId}&response_type=code&redirect_uri=urn:ietf:wg:oauth:2.0:oob`;35}36function viewer(options = {}) {37 return new Promise(async (resolve, reject) => {38 const query = `39 {40 viewer {41 id42 username43 first_name44 streak45 best_streak46 completed_todos_count47 streaking48 time_zone49 products {50 id51 name52 url53 hashtag54 }55 }56 }57 `;58 try {59 const json = await client().request(query);60 const data = {61 username: json.viewer.username,62 firstName: json.viewer.first_name,63 currentStreak: json.viewer.streak,64 bestStreak: json.viewer.best_streak,65 streaking: json.viewer.streaking,66 time_zone: json.viewer.time_zone,67 products: json.viewer.products,68 };69 return resolve(data);70 } catch (error) {71 if (error.type == 'system' && error.code == 'ENOTFOUND') {72 return reject('No internet connection');73 } else {74 return reject(error.response.errors[0].message);75 }76 }77 });78}79function uploadFile(presigned_url, file) {80 return new Promise((resolve, reject) => {81 const form = new FormData();82 for (let field of Object.keys(presigned_url.fields)) {83 form.append(field, presigned_url.fields[field]);84 }85 if (file.file.path) {86 // Actual image on disk87 form.append('file', fs.createReadStream(file.file.path));88 } else {89 // Pasted image90 var regex = /^data:(.+);base64,(.*)$/;91 var matches = file.base64.match(regex);92 var content_type = matches[1];93 var data = matches[2];94 var buffer = new Buffer(data, 'base64');95 form.append('file', buffer, {96 filename: file.file.name,97 contentType: content_type,98 knownLength: file.file.size,99 });100 }101 form.submit(presigned_url.url, function (error, response) {102 response.resume();103 if (error) reject(error);104 if (response.statusCode != 204) {105 reject('Invalid status code <' + response.statusCode + '>');106 }107 resolve();108 });109 });110}111function createTodo(todo = null, completed = true, files = []) {112 return new Promise(async (resolve, reject) => {113 let keys = new Array();114 if (files.length > 0) {115 for (const file of files) {116 const presigned_url = await createPresignedUrl(file.file.name);117 await uploadFile(presigned_url, file);118 keys.push({119 key: presigned_url.fields['key'],120 size: file.file.size,121 filename: file.file.name,122 });123 }124 }125 const mutation = `126 mutation createTodo($body: String!, $completed_at: DateTime, $attachments: [AttachmentInput], $broadcast: Boolean) {127 createTodo(input: { body: $body, completed_at: $completed_at, attachments: $attachments, broadcast: $broadcast }) {128 id129 body130 completed_at131 }132 }133 `;134 const variables = {135 body: todo,136 completed_at: completed ? new Date().toISOString() : null,137 attachments: keys,138 broadcast: store.get('broadcast'),139 };140 logger.log('Executing createTodo query', variables);141 const json = await client().request(mutation, variables);142 const data = {143 id: json.createTodo.id,144 completed_at: json.createTodo.completed_at,145 };146 logger.log('createTodo response: ', json);147 return resolve(data);148 });149}150function completeTodo(todo_id = null, files = [], options = {}) {151 return new Promise(async (resolve, reject) => {152 let keys = new Array();153 if (files.length > 0) {154 for (const file of files) {155 const presigned_url = await createPresignedUrl(file.file.name);156 await uploadFile(presigned_url, file);157 keys.push({158 key: presigned_url.fields['key'],159 size: file.file.size,160 filename: file.file.name,161 });162 }163 }164 const mutation = `165 mutation completeTodo($id: ID!, $attachments: [AttachmentInput], $broadcast: Boolean) {166 completeTodo(id: $id, attachments: $attachments, broadcast: $broadcast) {167 id168 completed_at169 }170 }171 `;172 const variables = {173 id: todo_id,174 attachments: keys,175 broadcast: store.get('broadcast'),176 };177 logger.log('Executing completeTodo query', variables);178 const json = await client().request(mutation, variables);179 const data = {180 id: json.completeTodo.id,181 completed_at: json.completeTodo.completed_at,182 };183 logger.log('completeTodo response: ', json);184 return resolve(data);185 });186}187function pendingTodos(filter = null, options = {}) {188 return new Promise(async (resolve, reject) => {189 const query = `190 query ($filter: String) {191 viewer {192 todos(filter: $filter, completed: false, limit: 100, order:"created_at:desc") {193 id194 body195 }196 }197 }198 `;199 const variables = {200 filter: filter.trim(),201 };202 const json = await client().request(query, variables);203 const data = json.viewer.todos;204 return resolve(data);205 });206}207function createPresignedUrl(filename) {208 logger.log('Creating presigned URL for ' + filename);209 return new Promise(async (resolve, reject) => {210 const mutation = `211 mutation createPresignedUrl($filename: String!) {212 createPresignedUrl(input:{ filename: $filename }) {213 url214 fields215 method216 headers217 }218 }219 `;220 const variables = {221 filename: filename,222 };223 const json = await client().request(mutation, variables);224 const data = {225 url: json.createPresignedUrl.url,226 fields: JSON.parse(json.createPresignedUrl.fields),227 method: json.createPresignedUrl.method,228 headers: JSON.parse(json.createPresignedUrl.headers),229 };230 return resolve(data);231 });232}233function getAccessToken(code) {234 logger.log('getAccessToken(' + code + ')');235 return new Promise((resolve, reject) => {236 let request_options = { method: 'POST', path: '/oauth/token' };237 if (devMode) {238 request_options.protocol = 'http:';239 request_options.hostname = 'wip.test';240 request_options.port = 5000;241 } else {242 request_options.protocol = 'https:';243 request_options.hostname = 'wip.co';244 request_options.port = 443;245 }246 const request = net.request(request_options);247 // request.setHeader('Content-Type', 'application/json');248 request.setHeader('Accept', 'application/json');249 request.setHeader('Content-Type', 'application/x-www-form-urlencoded');250 let body = '';251 request.on('response', (response) => {252 if (response.statusCode !== 200) {253 console.warn('Rejected with status code ' + response.statusCode);254 console.warn(response);255 return reject(response);256 }257 response.on('data', (chunk) => {258 body += chunk.toString();259 });260 response.on('end', () => {261 const json = JSON.parse(body);262 return resolve(json);263 });264 });265 const params = {266 client_id: clientId,267 code: code,268 grant_type: 'authorization_code',269 redirect_uri: 'urn:ietf:wg:oauth:2.0:oob',270 };271 // request.write(params.stringify());272 request.end(273 `client_id=${clientId}&code=${code}&grant_type=authorization_code&redirect_uri=urn:ietf:wg:oauth:2.0:oob`,274 );275 });276}277module.exports = {278 viewer: viewer,279 pendingTodos: pendingTodos,280 createTodo: createTodo,281 completeTodo: completeTodo,282 createPresignedUrl: createPresignedUrl,283 setApiKey: setApiKey,284 setClientId: setClientId,285 setDevMode: setDevMode,286 getDevMode: getDevMode,287 getAccessToken: getAccessToken,288 getOAuthURL: getOAuthURL,...

Full Screen

Full Screen

s3-upload-service.ts

Source:s3-upload-service.ts Github

copy

Full Screen

1import { UrlPath } from "../Interfaces/url-path";2import axios, { AxiosPromise } from "axios";3import { CreatePresignedUrlsRequest } from "../Interfaces/create-presigned-urls-requests";4import { CompleteMultiPartUploadRequest } from "../Interfaces/complete-multipart-upload-request";5import { CreatePresignedUrlsResponse } from "../Interfaces/create-presigned-urls-response";6import { StartMultiPartUploadRequest } from "../Interfaces/start-multi-part-upload-request";7import { PutMultiPartFileRequest } from "../Interfaces/put-multipart-file-request";8import { PutMultiPartFileresponse } from "../Interfaces/put-multipart-file-response";9class S3UploadService {10 private readonly startMultipartUploadUrl: string;11 private readonly createPresignedUrl: string;12 private readonly completeMultiPartUploadUrl: string;13 constructor(urlPaths: UrlPath){14 this.startMultipartUploadUrl = urlPaths.startMultiPartUploadUrl;15 this.createPresignedUrl = urlPaths.createPresignedUrl;16 this.completeMultiPartUploadUrl = urlPaths.completeMultiPartUploadUrl;17 };18 public StartMultiPartUpload({ fileName, folderName = "" }: StartMultiPartUploadRequest): AxiosPromise {19 return axios.post(this.startMultipartUploadUrl, {20 fileName,21 folderName22 });23 }24 public CreatePresignedUrls({ fileName, folderName, uploadId, partNumbers, contentType }: CreatePresignedUrlsRequest): AxiosPromise<Array<CreatePresignedUrlsResponse>> {25 return axios.post<Array<CreatePresignedUrlsResponse>>(this.createPresignedUrl, {26 uploadId,27 fileName,28 folderName,29 contentType,30 partNumbers31 });32 }33 public PutMultiPartFile({ presignedUrl, blob, headers} : PutMultiPartFileRequest) {34 return axios.put<PutMultiPartFileresponse>(presignedUrl, blob, {35 headers36 });37 }38 public ComplteMultiPartUpload({ fileName, folderName, partETags, uploadId } : CompleteMultiPartUploadRequest): AxiosPromise<void> {39 return axios.post<void>(this.completeMultiPartUploadUrl, {40 fileName,41 folderName,42 partETags,43 uploadId44 });45 }46}...

Full Screen

Full Screen

createPreSignedURL.test.ts

Source:createPreSignedURL.test.ts Github

copy

Full Screen

1import { APIGatewayProxyEvent } from 'aws-lambda'2import { handler } from './createPreSignedURL'3import * as data from '../../../test/events/file/createPreSignedURL/CreatePreSignedURL.json'4import * as data_invalid_body from '../../../test/events/file/createPreSignedURL/CreatePreSignedURL_invalid_body.json'5import * as data_missing_body from '../../../test/events/file/createPreSignedURL/CreatePreSignedURL_missing_body.json'6import * as data_missing_querystring from '../../../test/events/file/createPreSignedURL/CreatePreSignedURL_missing_querystring.json'7beforeAll(() => {8 process.env['S3_BUCKET_NAME'] = 'localbucket'9})10beforeEach(() => {11 jest.useFakeTimers()12})13describe('createPreSignedURL handler', () => {14 it('should return a pre-signed URL', async () => {15 const mockEvent: APIGatewayProxyEvent = data16 const result = await handler(mockEvent)17 expect(result).toHaveProperty('body')18 expect(result).toHaveProperty('headers', { 'content-type': 'application/json' })19 expect(result).toHaveProperty('statusCode', 200)20 const body = JSON.parse(result.body)21 expect(body).toHaveProperty('url')22 expect(body.url).toMatch(23 /localbucket\.s3\..*amazonaws\.com\/modules\/test\/test\/test\/test\/module\.zip\?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=.*%2F\d{8}%2F\w{2}-\w*-\d%2Fs3%2Faws4_request&X-Amz-Date=\d{8}T\d{6}Z&X-Amz-Expires=\d*&X-Amz-Signature=.{64}&X-Amz-SignedHeaders=host%3Bx-amz-tagging&x-amz-tagging=tags%3Dtrue/,24 )25 })26 it('should return an error when invalid body data', async () => {27 const mockEvent: APIGatewayProxyEvent = data_invalid_body28 const result = await handler(mockEvent)29 expect(result).toMatchSnapshot()30 })31 it('should return an error when missing body data', async () => {32 const mockEvent: APIGatewayProxyEvent = data_missing_body33 const result = await handler(mockEvent)34 expect(result).toMatchSnapshot()35 })36 it('should return an error when missing/invalid "type" querystring', async () => {37 const mockEvent: APIGatewayProxyEvent = data_missing_querystring38 const result = await handler(mockEvent)39 expect(result).toMatchSnapshot()40 })...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const chromeless = new Chromeless()2 .type('chromeless', 'input[name="q"]')3 .press(13)4 .wait('#resultStats')5 .screenshot()6await chromeless.end()7const express = require('express')8const chromeless = require('./test.js')9const app = express()10app.get('/', (req, res) => {11 res.send(chromeless.screenshot())12})13app.listen(3000, () => {14 console.log('Example app listening on port 3000!')15})

Full Screen

Using AI Code Generation

copy

Full Screen

1const chromeless = new Chromeless();2 .type('chromeless', 'input[name="q"]')3 .press(13)4 .wait('#resultStats')5 .createPresignedURL();6console.log(url);7const chromeless = new Chromeless();8 .type('chromeless', 'input[name="q"]')9 .press(13)10 .wait('#resultStats')11 .createPresignedURL();12console.log(url);13const chromeless = new Chromeless();14 .type('chromeless', 'input[name="q"]')15 .press(13)16 .wait('#resultStats')17 .createPresignedURL();18console.log(url);19const chromeless = new Chromeless();20 .type('chromeless', 'input[name="q"]')21 .press(13)22 .wait('#resultStats')23 .createPresignedURL();24console.log(url);25const chromeless = new Chromeless();26 .type('chromeless', 'input[name="q"]')27 .press(13)28 .wait('#resultStats')29 .createPresignedURL();30console.log(url);31const chromeless = new Chromeless();32 .type('chromeless', 'input[name="q"]')33 .press(13)34 .wait('#resultStats')35 .createPresignedURL();36console.log(url);37const chromeless = new Chromeless();38 .type('chromeless', 'input[name="q"]')

Full Screen

Using AI Code Generation

copy

Full Screen

1const chromeless = require('chromeless')()2const createPresignedURL = require('./createPresignedURL')3const run = async () => {4 const url = await createPresignedURL()5 .goto(url)6 .screenshot()7 await chromeless.end()8}9run().catch(console.error.bind(console))10const AWS = require('aws-sdk')11const chromeless = require('chromeless')()12const s3 = new AWS.S3()13const createPresignedURL = async () => {14 .screenshot()15 const params = {16 }17 const upload = await s3.upload(params).promise()18}

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run chromeless automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful