Best JavaScript code snippet using qawolf
pinNftMetadataIPFS.js
Source:pinNftMetadataIPFS.js
1import pinataSDK from '@pinata/sdk';2import formidable from 'formidable';3const fs = require('fs');4const path = require('path');5const os = require('os');6// Configuration to use formidable7export const config = {8 api: {9 bodyParser: false10 }11};12// Helper to get authorName initials13const getInitials = (fullName) => {14 const nameArr = fullName.split('')15 let initials = nameArr.filter(char => {16 return /[A-Z]/.test(char)17 })18 return initials.join('')19}20// Format metadata name to EIP-1155 standards (64 hex characters length leading by 0 / [0-9a-f] )21const formatName = (str) => {22 // 1-S 2-D 3-N 4-T 5-R 6-Y 7-L 8-C Other-923 let result24 let regex = /[^0-9a-fsdntryls]/g25 let coreString = str.split(" ").join("").toLowerCase().slice(0,63)26 coreString = coreString27 .replaceAll("s","1")28 .replaceAll("d","2")29 .replaceAll("n","3")30 .replaceAll("t","4")31 .replaceAll("r","5")32 .replaceAll("y","6")33 .replaceAll("l","7")34 .replaceAll("s","8")35 .replaceAll(regex, "9")36 let missingCount = 63 - coreString.length37 let missingZero = []38 Array.from(Array(missingCount).keys()).map(value => missingZero.push("0"))39 result = `0${missingZero.join("")}${coreString}.json`40 console.log(result);41 return result42}43export default async function pinNftMetadataIPFS(req, res) {44 //! Initialisation Pinata SDK45 const pinata = pinataSDK(process.env.PINATA_API_KEY, process.env.PINATA_API_SECRET);46 const prefixTempFolder = "temp-nftmetadata"47 let tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), prefixTempFolder))48 console.log(tmpDir);49 //! Get POST file informations and file - formidable parse is asynchrone50 const createMetadataJSON = await new Promise((res, rej) => {51 const form = new formidable.IncomingForm()52 form.parse(req, function(err, fields, files) {53 const metadataNFT = `54 {55 "description":"${fields.description}",56 "external_url": "${fields.external_url}",57 "image":"${fields.previewIpfsURL}",58 "name":"${fields.title}",59 "animation_url":"${fields.nftBookURI}",60 "attributes": [61 {62 "trait_type": "Language", 63 "value": "${fields.language}"64 }, 65 {66 "trait_type": "Format", 67 "value": "${fields.format}"68 }, 69 {70 "trait_type": "Editor", 71 "value": "${fields.editorName}"72 },73 {74 "trait_type": "Serie", 75 "value": "${fields.serie}"76 },77 {78 "trait_type": "Special Edition", 79 "value": "${fields.specialEdition}"80 }, 81 {82 "trait_type": "Category #1", 83 "value": "${fields.category1}"84 }, 85 {86 "trait_type": "Category #2", 87 "value": "${fields.category2}"88 }, 89 {90 "display_type": "date",91 "trait_type": "NFT Publication Date", 92 "value": "${fields.timestamp}"93 },94 {95 "trait_type": "NFT Publication Rights", 96 "value": "${fields.rights}"97 }98 ]99 }100 `101 const fileName = formatName(`${fields.title}${getInitials(fields.authorName)}${fields.editorName}${fields.collectionName}`)102 const jsonObject = JSON.parse(metadataNFT)103 const jsonContent = JSON.stringify(jsonObject)104 const newFile = fs.writeFileSync(path.join(tmpDir, fileName), jsonContent, 'utf8', (err) => {105 if (err) throw err;106 console.log('Metadata file created successfully.');107 })108 109 const readableStream = fs.createReadStream(path.join(tmpDir, fileName))110 // console.log("Metadata file created")111 const options = {112 pinataMetadata: {113 name: fileName,114 keyvalues: {115 type: "metadata nft book",116 clientAddress: fields.clientAddress,117 format: fields.format,118 title: fields.title,119 authorName: fields.authorName,120 editorName: fields.editorName,121 collection: fields.collectionName,122 tome: fields.tome,123 rights: fields.rights124 }125 },126 }127 return res({128 readableStream: readableStream,129 options: options130 })131 })132 })133 134 try {135 const metadataJSON = createMetadataJSON.readableStream136 const pinataOptions = createMetadataJSON.options137 const pinMetadataToIPFS = await pinata.pinFileToIPFS(metadataJSON, pinataOptions)138 res.status(200).json(pinMetadataToIPFS)139 } catch (error) {140 console.log(error);141 res.status(500).send({ error: "Failed to upload NFT Metadata" })142 }143 finally {144 try {145 if (tmpDir) {146 fs.rmSync(tmpDir, { recursive: true });147 }148 }149 catch (err) {150 console.error(`An error has occurred while removing the temp folder at ${tmpDir}. Please remove it manually. Error: ${err}`);151 }152 }...
pinContractMetadataIPFS.js
Source:pinContractMetadataIPFS.js
1import pinataSDK from '@pinata/sdk';2import formidable from 'formidable';3const fs = require('fs');4const path = require('path');5const os = require('os');6// Configuration to use formidable7export const config = {8 api: {9 bodyParser: false10 }11};12// Helper to get authorName initials13const getInitials = (fullName) => {14 const nameArr = fullName.split('')15 let initials = nameArr.filter(char => {16 return /[A-Z]/.test(char)17 })18 return initials.join('')19}20export default async function pinContractMetadataIPFS(req, res) {21 //! Initialisation Pinata SDK22 const pinata = pinataSDK(process.env.PINATA_API_KEY, process.env.PINATA_API_SECRET);23 const prefixTempFolder = "temp-contractmetadata"24 let tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), prefixTempFolder))25 console.log(tmpDir);26 //! Get POST file informations and file - formidable parse is asynchrone27 const createMetadataJSON = await new Promise((res, rej) => {28 const form = new formidable.IncomingForm()29 form.parse(req, function(err, fields, files) {30 const metadataContract = `31 {32 "name":"${fields.collectionName}",33 "description":"${fields.collectionDesc}",34 "image":"${fields.collectionImgIpfsURL}",35 "external_link": "${fields.collectionLink}",36 "seller_fee_basis_points":"${fields.royaltyFeeInBips}",37 "fee_recipient":"${fields.clientAddress}"38 }39 `40 const fileName = `metaContract-${fields.collectionName}-${getInitials(fields.authorName)}-Ed${fields.editorName}.json`41 const jsonObject = JSON.parse(metadataContract)42 const jsonContent = JSON.stringify(jsonObject)43 const newFile = fs.writeFileSync(path.join(tmpDir, fileName), jsonContent, 'utf8', (err) => {44 if (err) throw err;45 console.log('Metadata file created successfully.');46 })47 48 const readableStream = fs.createReadStream(path.join(tmpDir, fileName))49 console.log("Metadata file created")50 const options = {51 pinataMetadata: {52 name: fileName,53 keyvalues: {54 type: "metadata collection",55 clientAddress: fields.clientAddress,56 collection: fields.collectionName,57 link: fields.collectionLink,58 authorName: fields.authorName,59 editorName: fields.editorName,60 rights: fields.rights,61 }62 },63 }64 return res({65 readableStream: readableStream,66 options: options67 })68 })69 })70 71 try {72 const metadataJSON = createMetadataJSON.readableStream73 const pinataOptions = createMetadataJSON.options74 const pinMetadataToIPFS = await pinata.pinFileToIPFS(metadataJSON, pinataOptions)75 res.status(200).json(pinMetadataToIPFS)76 } catch (error) {77 console.log(error);78 res.status(500).send({ error: "Failed to upload NFT Metadata" })79 }80 finally {81 try {82 if (tmpDir) {83 fs.rmSync(tmpDir, { recursive: true });84 }85 }86 catch (err) {87 console.error(`An error has occurred while removing the temp folder at ${tmpDir}. Please remove it manually. Error: ${err}`);88 }89 }...
box.js
Source:box.js
1const fs = require('fs')2const TEMP_PATH = '/tmp/temp.pdf'3var BoxSDK = require('box-node-sdk');4var jsonConfig = require('../config.json');5var sdk = BoxSDK.getPreconfiguredInstance(jsonConfig);6var client = sdk.getAppAuthClient('enterprise');7const USER_ID = '1958091740'8client.asUser(USER_ID);9class Box {10 constructor(filesReader, body) {11 const eventBody = JSON.parse(body);12 this.fileId = eventBody.source.id;13 this.filesReader = filesReader;14 }15 /**16 * Download Document from Box using the Skills Kit FilesReader class.17 */18 async downloadFileFromBox() {19 // get box file read stream and write to local temp file20 const readStream = await this.filesReader.getContentStream();21 const writeStream = fs.createWriteStream(TEMP_PATH);22 const stream = readStream.pipe(writeStream);23 // wait for stream write to 'finish'24 await new Promise((resolve, reject) => {25 stream.on('finish', function () {26 resolve()27 });28 });29 return TEMP_PATH;30 }31 /**32 * Attach skills metadata to file using the Skills Kit skillsWriter class.33 */34 async attachMetadataCard(rossumJson) {35 console.log("FILE ID:", this.fileId);36 const metadataValues = createMetadataJSON(rossumJson);37 const result = await client.files.addMetadata(this.fileId, client.metadata.scopes.ENTERPRISE, "invoicedetails", metadataValues);38 console.log("RESULT:", result);39 }40}41function createMetadataJSON(rossumJson) {42 const metadata = {43 invoiceNumber: "", 44 customerNumber: "",45 issueDate: "",46 dueDate: "", 47 terms: "",48 totalAmount: "",49 amountPaid: "", 50 amountDue: "", 51 senderName: "", 52 recipientName: "",53 taxTotal: "",54 orderNumber: ""55 };56 const keywords = {57 "invoice_id": "invoiceNumber",58 "customer_id": "customerNumber",59 "date_issue": "issueDate",60 "date_due": "dueDate",61 "terms": "terms",62 "amount_total": "totalAmount",63 "amount_paid": "amountPaid",64 "amount_due": "amountDue",65 "sender_name": "senderName",66 "recipient_name": "recipientName",67 "tax_detail_total": "taxTotal",68 "order_id": "orderNumber"69 }70 Object.keys(keywords).forEach((key) => {71 if (rossumJson[key]) {72 metadata[keywords[key]] = rossumJson[key];73 }74 });75 return metadata;76}...
createMetadataJson-test.ts
Source:createMetadataJson-test.ts
1import { createMetadataJson } from '../createMetadataJson';2describe(createMetadataJson, () => {3 it(`writes metadata without file hashes`, async () => {4 // Should not throw5 await createMetadataJson({6 fileNames: {7 ios: 'ios-xxfooxxbarxx.js',8 },9 bundles: {10 ios: {11 assets: [{ type: 'font' } as any],12 },13 },14 });15 });16 it(`writes metadata manifest`, async () => {17 const metadata = await createMetadataJson({18 fileNames: {19 ios: 'ios-xxfooxxbarxx.js',20 },21 bundles: {22 ios: {23 assets: [{ type: 'image', fileHashes: ['foobar', 'other'] } as any],24 },25 },26 });27 expect(metadata).toStrictEqual({28 bundler: expect.any(String),29 fileMetadata: {30 ios: {31 assets: [...
xmindmark-to-xmind.ts
Source:xmindmark-to-xmind.ts
...11 "metadata.json": {}12 }13 })14}15function createMetadataJson() {16 return JSON.stringify({})17}18export async function parseXMindMarkToXMindFile(xmindMarkFileContent: string): Promise<ArrayBuffer> {19 const sheetModel = createMapByXMindMark(xmindMarkFileContent)20 const xmindFolder = {21 'content.json': createContentJson(sheetModel),22 'manifest.json': createManifestJson(),23 'metadata.json': createMetadataJson()24 }25 return await Object.entries(xmindFolder)26 .reduce((zip, [filename, content]) => zip.file(filename, content), new JSZip())27 .generateAsync({ type: 'arraybuffer', compression: 'DEFLATE', compressionOptions: { level: 6 } })...
Using AI Code Generation
1const { createMetadataJson } = require("qawolf");2const fs = require("fs");3const path = require("path");4async function createMetadata() {5 const metadata = await createMetadataJson();6 const metadataFilePath = path.join(__dirname, "metadata.json");7 fs.writeFileSync(metadataFilePath, JSON.stringify(metadata, null, 2));8}9createMetadata();
Using AI Code Generation
1const qawolf = require("qawolf");2const { createMetadataJson } = qawolf;3const path = require("path");4(async () => {5 await qawolf.create(metadata);6})();7(async () => {8 await qawolf.create(metadata, { testDir: path.join(__dirname, "test") });9})();10(async () => {11 await qawolf.create(metadata, {12 testDir: path.join(__dirname, "test"),13 });14})();15(async () => {16 await qawolf.create(metadata, {17 testDir: path.join(__dirname, "test"),18 testPath: path.join(__dirname, "test"),19 });20})();21(async () => {22 await qawolf.create(metadata, {23 testDir: path.join(__dirname, "test"),24 testPath: path.join(__dirname, "test"),25 code: "const { test } = require('qawolf');",26 });27})();28(async () => {29 await qawolf.create(metadata, {30 testDir: path.join(__dirname, "test"),31 testPath: path.join(__dirname, "test"),32 code: "const { test } = require('qawolf');",33 });34})();35(async () => {
Using AI Code Generation
1const { createMetadataJson } = require('qawolf');2const metadata = await createMetadataJson('chrome');3console.log(metadata);4const { createMetadataJson } = require('qawolf');5const metadata = await createMetadataJson('chrome', { headless: false });6console.log(metadata);7const { createMetadataJson } = require('qawolf');8const metadata = await createMetadataJson('chrome', { headless: false, slowMo: 500 });9console.log(metadata);10const { createMetadataJson } = require('qawolf');11console.log(metadata);12const { createMetadataJson } = require('qawolf');13console.log(metadata);14const { createMetadataJson } = require('qawolf');15console.log(metadata);16const { createMetadataJson } = require('qawolf');17const metadata = await createMetadataJson('chrome',
Using AI Code Generation
1const { createMetadataJson } = require("qawolf");2createMetadataJson({ name: "test", path: "test.json" });3{4 {5 }6}7const { createTests } = require("qawolf");8createTests({ path: "test.json" });9const { createTest } = require("qawolf");10createTest({ name: "test", path: "test.json" });
Using AI Code Generation
1const qawolf = require("qawolf");2const path = require("path");3const fs = require("fs");4const { createMetadataJson } = qawolf;5async function createMetadata() {6 const metadata = await createMetadataJson({7 code: `const qawolf = require("qawolf");8 const browser = await qawolf.launch();9 const page = await qawolf.context(browser);10 await qawolf.click(page, "#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input");11 await qawolf.type(page, "#tsf > div:nth-child(2) > div > div.RNNXgb > div > div.a4bIc > input", "qawolf");12 await qawolf.click(page, "#tsf > div:nth-child(2) > div > div.FPdoLc.lJ9FBc > center > input[type="submit"]:nth-child(1)");13 await qawolf.click(page, "#rso > div:nth-child(1) > div > div:nth-child(1) > div > div > div.r > a > h3");
Using AI Code Generation
1const { createMetadataJson } = require('@qawolf/create-metadata-json');2console.log(metadata);3const { createMetadataJson } = require('@qawolf/create-metadata-json');4console.log(metadata);5const { createMetadataJson } = require('@qawolf/create-metadata-json');6console.log(metadata);7const { createMetadataJson } = require('@qawolf/create-metadata-json');8console.log(metadata);9const { createMetadataJson } = require('@qawolf/create-metadata-json');10console.log(metadata);11const { createMetadataJson } = require('@qawolf/create-metadata-json');12console.log(metadata);13const { createMetadataJson } = require('@qawolf/create-metadata-json');14console.log(metadata);15const { createMetadataJson } = require('@qawolf/create-metadata-json');16console.log(metadata);17const { createMetadataJson } = require('@qawolf/create-metadata-json');18console.log(metadata);19const { createMetadataJson } = require('@qawolf/create-metadata-json');20console.log(metadata);
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.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!