Snippets Collections
  const books = [
    {
      title: 'Algorithms',
      author: ['Robert Sedgewick', 'Kevin Wayne'],
      publisher: 'Addison-Wesley Professional',
      publicationDate: '2011-03-24',
      edition: 4,
      keywords: [
        'computer science',
        'programming',
        'algorithms',
        'data structures',
        'java',
        'math',
        'software',
        'engineering',
      ],
      pages: 976,
      format: 'hardcover',
      ISBN: '9780321573513',
      language: 'English',
      programmingLanguage: 'Java',
      onlineContent: true,
      thirdParty: {
        goodreads: {
          rating: 4.41,
          ratingsCount: 1733,
          reviewsCount: 63,
          fiveStarRatingCount: 976,
          oneStarRatingCount: 13,
        },
      },
      highlighted: true,
    },
    {
      title: 'Structure and Interpretation of Computer Programs',
      author: [
        'Harold Abelson',
        'Gerald Jay Sussman',
        'Julie Sussman (Contributor)',
      ],
      publisher: 'The MIT Press',
      publicationDate: '2022-04-12',
      edition: 2,
      keywords: [
        'computer science',
        'programming',
        'javascript',
        'software',
        'engineering',
      ],
      pages: 640,
      format: 'paperback',
      ISBN: '9780262543231',
      language: 'English',
      programmingLanguage: 'JavaScript',
      onlineContent: false,
      thirdParty: {
        goodreads: {
          rating: 4.36,
          ratingsCount: 14,
          reviewsCount: 3,
          fiveStarRatingCount: 8,
          oneStarRatingCount: 0,
        },
      },
      highlighted: true,
    },
    {
      title: "Computer Systems: A Programmer's Perspective",
      author: ['Randal E. Bryant', "David Richard O'Hallaron"],
      publisher: 'Prentice Hall',
      publicationDate: '2002-01-01',
      edition: 1,
      keywords: [
        'computer science',
        'computer systems',
        'programming',
        'software',
        'C',
        'engineering',
      ],
      pages: 978,
      format: 'hardcover',
      ISBN: '9780130340740',
      language: 'English',
      programmingLanguage: 'C',
      onlineContent: false,
      thirdParty: {
        goodreads: {
          rating: 4.44,
          ratingsCount: 1010,
          reviewsCount: 57,
          fiveStarRatingCount: 638,
          oneStarRatingCount: 16,
        },
      },
      highlighted: true,
    },
    {
      title: 'Operating System Concepts',
      author: ['Abraham Silberschatz', 'Peter B. Galvin', 'Greg Gagne'],
      publisher: 'John Wiley & Sons',
      publicationDate: '2004-12-14',
      edition: 10,
      keywords: [
        'computer science',
        'operating systems',
        'programming',
        'software',
        'C',
        'Java',
        'engineering',
      ],
      pages: 921,
      format: 'hardcover',
      ISBN: '9780471694663',
      language: 'English',
      programmingLanguage: 'C, Java',
      onlineContent: false,
      thirdParty: {
        goodreads: {
          rating: 3.9,
          ratingsCount: 2131,
          reviewsCount: 114,
          fiveStarRatingCount: 728,
          oneStarRatingCount: 65,
        },
      },
    },
    {
      title: 'Engineering Mathematics',
      author: ['K.A. Stroud', 'Dexter J. Booth'],
      publisher: 'Palgrave',
      publicationDate: '2007-01-01',
      edition: 14,
      keywords: ['mathematics', 'engineering'],
      pages: 1288,
      format: 'paperback',
      ISBN: '9781403942463',
      language: 'English',
      programmingLanguage: null,
      onlineContent: true,
      thirdParty: {
        goodreads: {
          rating: 4.35,
          ratingsCount: 370,
          reviewsCount: 18,
          fiveStarRatingCount: 211,
          oneStarRatingCount: 6,
        },
      },
      highlighted: true,
    },
    {
      title: 'The Personal MBA: Master the Art of Business',
      author: 'Josh Kaufman',
      publisher: 'Portfolio',
      publicationDate: '2010-12-30',
      keywords: ['business'],
      pages: 416,
      format: 'hardcover',
      ISBN: '9781591843528',
      language: 'English',
      thirdParty: {
        goodreads: {
          rating: 4.11,
          ratingsCount: 40119,
          reviewsCount: 1351,
          fiveStarRatingCount: 18033,
          oneStarRatingCount: 1090,
        },
      },
    },
    {
      title: 'Crafting Interpreters',
      author: 'Robert Nystrom',
      publisher: 'Genever Benning',
      publicationDate: '2021-07-28',
      keywords: [
        'computer science',
        'compilers',
        'engineering',
        'interpreters',
        'software',
        'engineering',
      ],
      pages: 865,
      format: 'paperback',
      ISBN: '9780990582939',
      language: 'English',
      thirdParty: {
        goodreads: {
          rating: 4.7,
          ratingsCount: 253,
          reviewsCount: 23,
          fiveStarRatingCount: 193,
          oneStarRatingCount: 0,
        },
      },
    },
    {
      title: 'Deep Work: Rules for Focused Success in a Distracted World',
      author: 'Cal Newport',
      publisher: 'Grand Central Publishing',
      publicationDate: '2016-01-05',
      edition: 1,
      keywords: ['work', 'focus', 'personal development', 'business'],
      pages: 296,
      format: 'hardcover',
      ISBN: '9781455586691',
      language: 'English',
      thirdParty: {
        goodreads: {
          rating: 4.19,
          ratingsCount: 144584,
          reviewsCount: 11598,
          fiveStarRatingCount: 63405,
          oneStarRatingCount: 1808,
        },
      },
      highlighted: true,
    },
  ];




 function printBookAuthorsCount(title, ...authors) { // authors can be more than 1 param
    return `The book ${title} has ${authors.length} authors`;
  }

  const { title: book3Title, author: authors } = books[2];

  const bookAuthor = printBookAuthorsCount(
    book3Title,
    'Robert Sedgewick', //rest param 1
    'Kevin Wayne' //rest param 2
  );
  console.log(bookAuthor);
   const testObj = {
    name: 'David',
    movie: 'fight club',
    active: true,
  };

  const testObj2 = {
    name: 'kevin',
    movie: 'Bladerunner',
    active: false,
  };



// using rest only
const combined = []; //empty array

  function makeArrayFromMUtipleObjects(...args) {
    for (let item of args) {
      // will have two separate objects
      combined.push(item); // push into the empty arry
    }
  }

  console.log(combined); 




// using rest and another param

 const anotherArray = [];

 function makeArray(array, ...itemsToAdd) {
    return array.concat(itemsToAdd);
  }

 const made = makeArray(anotherArray, testObj, testObj2);
 console.log(made);
//---------------------------------------------------------
// REST service to add an image to a PDF document
//---------------------------------------------------------
const express = require('express');
const cors = require('cors');
const bodyParser = require('body-parser');
const fs = require('fs');
const path = require('path');
const pdfLib = require('pdf-lib');

const app = express();
const port = process.env.PORT || 3000;

// Middleware
app.use(cors());
app.use(bodyParser.json());

// Routes
app.post('/api/addImageToPDF', async function(req, res) {
	const { pdfPath, imagePath, outputName } = req.body;

	// Read PDF file
	const pdfData = await fs.promises.readFile(pdfPath);

	// Read image file
	const imageData = await fs.promises.readFile(imagePath);

	// Load PDF document
	const pdfDoc = await pdfLib.PDFDocument.load(pdfData);

	// Embed image in PDF
	const image = await pdfDoc.embedPng(imageData);
	const page = pdfDoc.getPages()[0];
	const { width, height } = page.getSize();
	page.drawImage(image, {
		x: 0,
		y: height - image.height,
		width: image.width,
		height: image.height,
	});

	// Save modified PDF
	const outputPath = path.join(__dirname, 'modified', outputName);
	const modifiedPdfBytes = await pdfDoc.save();
	await fs.promises.writeFile(outputPath, modifiedPdfBytes);

	// Send response
	res.json({ success: true, message: 'Image added to PDF', url: `http://localhost:${port}/api/getModifiedPDF/${outputName}` });
});

app.get('/api/getModifiedPDF/:fileName', async function(req, res) {
	const { fileName } = req.params;
	const filePath = path.join(__dirname, 'arhiviran', `${fileName}-arhivirano-${new Date().toISOString().replace(/[^\d]/g, '')}.pdf`);
	
	// Read modified PDF file
	const pdfData = await fs.promises.readFile(filePath);

	// Create blob from PDF data
	const blob = new Blob([pdfData], { type: 'application/pdf' });

	// Set response headers
	res.setHeader('Content-Type', 'application/pdf');
	res.setHeader('Content-Disposition', 'attachment; filename=modified.pdf');
	res.setHeader('Content-Length', pdfData.length);

	// Send response
	res.send(blob);
});

// Listen command
app.listen(port, function() {
	console.log(`Server is running on port ${port}`);
});
//---------------------------------------------------------


//---------------------------------------------------------
// How to call the service (client side) with a file name
//---------------------------------------------------------
// Create a FormData object to send the file data
var fileData = new FormData();
fileData.append('file', 'sample.pdf');

// Send the AJAX request to modify the PDF file
$.ajax({
	url: '/modify-pdf',
	method: 'POST',
	data: fileData,
	processData: false,
	contentType: false,
	success: function(data) {
		console.log('File modified successfully. Modified file URL:', data.url);
	},
	error: function() {
		console.error('Error modifying file.');
	}
});

//---------------------------------------------------------
// Send the AJAX request to get the modified PDF file as a blob
//---------------------------------------------------------
$.ajax({
	url: '/get-modified-pdf',
	method: 'GET',
	success: function(data) {
		// Create a blob URL from the received blob
		var blobUrl = URL.createObjectURL(data);
		
		// Create an anchor element to download the file
		var downloadLink = $('<a>')
			.attr('href', blobUrl)
			.attr('download', 'modified.pdf')
			.text('Download modified PDF file');
			
		// Add the anchor element to the page
		$('body').append(downloadLink);
	},
	error: function() {
		console.error('Error getting modified file.');
	}
});
//---------------------------------------------------------
// add this to functions.php
//register acf fields to Wordpress API
//https://support.advancedcustomfields.com/forums/topic/json-rest-api-and-acf/

function acf_to_rest_api($response, $post, $request) {
    if (!function_exists('get_fields')) return $response;

    if (isset($post)) {
        $acf = get_fields($post->id);
        $response->data['acf'] = $acf;
    }
    return $response;
}
add_filter('rest_prepare_post', 'acf_to_rest_api', 10, 3);
const express = require('express');
const router = express.Router();

// this is our crud route so it'll have the most routes
// SIGNTAURE TYPE ENDPOINT
// @route       GET api/contacts
// @desc        get user's contacts
// @access      private (theses are all private to user so all private)
// we said anything that goes to this file is coming from /api/auth so we just need a slash
router.get('/', (req, res) => {
    res.send(`Get all the user's contacts`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       POST api/contacts
// @desc        add a new contact
// @access      private 
router.post('/', (req, res) => {
    res.send(`Add a new contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       PUT api/contacts/:id (we need to id which contact is getting updated)
// @desc        update contact
// @access      private 
router.put('/:id', (req, res) => {
    res.send(`Update a contact`)
})

// SIGNTAURE TYPE ENDPOINT
// @route       DELETE api/contacts/:id (we need to id which contact is getting deleted)
// @desc        delete contact
// @access      private 
router.delete('/:id', (req, res) => {
    res.send(`DESTROY a contact`)
})

// export router so we can access ittttt
module.exports = router
star

Fri Jun 21 2024 00:02:46 GMT+0000 (Coordinated Universal Time)

#functions #...args #rest
star

Thu Jun 20 2024 23:17:24 GMT+0000 (Coordinated Universal Time)

#functions #...args #rest
star

Fri May 12 2023 11:15:35 GMT+0000 (Coordinated Universal Time)

#javascript #nodejs #rest
star

Wed Nov 30 2022 17:21:52 GMT+0000 (Coordinated Universal Time) https://stackoverflow.com/questions/56473929/how-to-expose-all-the-acf-fields-to-wordpress-rest-api-in-both-pages-and-custom

#php #wp #acf #rest
star

Thu Jul 15 2021 09:01:59 GMT+0000 (Coordinated Universal Time)

#nodejs #api #routing #rest
star

Thu Jul 16 2020 13:01:21 GMT+0000 (Coordinated Universal Time) https://github.com/an-tao/drogon

#c++ #web #rest

Save snippets that work with our extensions

Available in the Chrome Web Store Get Firefox Add-on Get VS Code extension