diff --git a/README.md b/README.md index eba1906cd0cf6fe0af11689384dc1d6060d8f28a..b6b645ef0175679adad152d5ef828705c9cc45c3 100644 --- a/README.md +++ b/README.md @@ -9,6 +9,7 @@ PORT=8080 SERVER_URL=localhost NODE_ENV=development DB=mongodb://localhost:27017/test +LOCAL=true ``` Next, you have to setup your MongoDB properly. diff --git a/server/data.json b/server/data.json new file mode 100644 index 0000000000000000000000000000000000000000..752c792beee07f637203a519fc31f2e30929600e --- /dev/null +++ b/server/data.json @@ -0,0 +1,62 @@ +{ + "names": [ + "Damian", "Polly", "Vivan", "Felisa", "John", "Mack", "Lynette", "Etsuko", + "Ashely", "Willard", "Junie", "Guy", "Wendolyn", "Venessa", "Damaris", "Jenell", + "Alysha", "Lakiesha", "Jacklyn", "Ruby", "Janise", "Annemarie", "Tobie", "Felton", + "Jacinto", "Emerita", "Almeta", "Han", "Sidney", "Tyree", "Cedric", "Ina", "Art", + "Danyelle", "Georgeann", "September", "Yoko", "Marcelino", "Jillian", "Terrie", + "Mandi", "Lola", "Arianne", "Lettie", "Lauri", "Sage", "Pablo", "Donnette", "Muoi" + ], + "facts": [ + "A cat will tremble or shiver when it is extreme pain.", + "Cat's urine glows under a black light.", + "The name \"jaguar\" comes from a Native American word meaning \"he who kills with one leap\".", + "Cats lose almost as much fluid in the saliva while grooming themselves as they do through urination.", + "Retractable claws are a physical phenomenon that sets cats apart from the rest of the animal kingdom. I n the cat family, only cheetahs cannot retract their claws.", + "Cats can judge within 3 inches the precise location of a sound being made 1 yard away.", + "A cat's hearing is much more sensitive than humans and dogs.", + "A cat has more bones than a human; humans have 206, and the cat - 230.", + "Miacis, the primitive ancestor of cats, was a small, tree-living creature of the late Eocene period, some 45 to 50 million years ago.", + "The smallest pedigreed cat is a Singapura, which can weigh just 4 lbs (1.8 kg), or about five large cans of cat food. The largest pedigreed cats are Maine Coon cats, which can weigh 25 lbs (11.3 kg), or nearly twice as much as an average cat weighs.", + "Ancient Egyptian family members shaved their eyebrows in mourning when the family cat died.", + "A cat lover is called an Ailurophilia (Greek: cat+lover).", + "All cats have claws, and all except the cheetah sheath them when at rest.", + "Baking chocolate is the most dangerous chocolate to your cat.", + "Today there are about 100 distinct breeds of the domestic cat.", + "The cat's footpads absorb the shocks of the landing when the cat jumps.", + "The technical term for a cat’s hairball is a “bezoar.”", + "Normal body temperature for a cat is 102 degrees F.", + "The silks created by weavers in Baghdad were inspired by the beautiful and varied colors and markings of cat coats. These fabrics were called \\tabby\\\" by European traders.\"\"\"", + "Unlike dogs, cats do not have a sweet tooth. Scientists believe this is due to a mutation in a key taste receptor.", + "The first official cat show in the UK was organised at Crystal Palace in 1871.", + "The average litter of kittens is between 2 - 6 kittens.", + "Cats have been domesticated for half as long as dogs have been.", + "Cheetahs do not roar, as the other big cats do. Instead, they purr.", + "Since cats are so good at hiding illness, even a single instance of a symptom should be taken very seriously.", + "Cats are subject to gum disease and to dental caries. They should have their teeth cleaned by the vet or the cat dentist once a year.", + "There are up to 60 million feral cats in the United States alone.", + "In 1888, more than 300,000 mummified cats were found an Egyptian cemetery. They were stripped of their wrappings and carted off to be used by farmers in England and the U.S. for fertilizer.", + "The ability of a cat to find its way home is called “psi-traveling.” Experts think cats either use the angle of the sunlight to find their way or that cats have magnetized cells in their brains that act as compasses.", + "Some notable people who disliked cats: Napoleon Bonaparte, Dwight D. Eisenhower, Hitler.", + "Cats lap liquid from the underside of their tongue, not from the top.", + "Statistics indicate that animal lovers in recent years have shown a preference for cats over dogs!", + "When a domestic cat goes after mice, about 1 pounce in 3 results in a catch.", + "A cat's normal temperature varies around 101 degrees Fahrenheit.", + "A cat's whiskers are thought to be a kind of radar, which helps a cat gauge the space it intends to walk through.", + "Cat paws act as tempetature regulators, shock absorbers, hunting and grooming tools, sensors, and more", + "The ancestor of all domestic cats is the African Wild Cat which still exists today.", + "A 2007 Gallup poll revealed that both men and women were equally likely to own a cat.", + "Cats have the largest eyes of any mammal.", + "Cats can predict earthquakes. We humans are not 100% sure how they do it. There are several different theories.", + "Cat families usually play best in even numbers. Cats and kittens should be aquired in pairs whenever possible.", + "The earliest ancestor of the modern cat lived about 30 million years ago. Scientists called it the Proailurus, which means “first cat” in Greek. The group of animals that pet cats belong to emerged around 12 million years ago.", + "A domestic cat can run at speeds of 30 mph.", + "A cat uses its whiskers for measuring distances. The whiskers of a cat are capable of registering very small changes in air pressure.", + "Female felines are \\superfecund", + "Approximately 40,000 people are bitten by cats in the U.S. annually.", + "The world’s rarest coffee, Kopi Luwak, comes from Indonesia where a wildcat known as the luwak lives. The cat eats coffee berries and the coffee beans inside pass through the stomach. The beans are harvested from the cat’s dung heaps and then cleaned and roasted. Kopi Luwak sells for about $500 for a 450 g (1 lb) bag.", + "If your cat snores, or rolls over on his back to expose his belly, it means he trusts you.", + "The cheetah is the world's fastest land mammal. It can run at speeds of up to 70 miles an hour (113 kilometers an hour).", + "A cat’s jaw can’t move sideways, so a cat can’t chew large chunks of food." + ] +} \ No newline at end of file diff --git a/server/server.js b/server/server.js index 086923ed5a7c9af26158ce18c4cf3313d2b606f2..63012ce350d6abe71eec6725ee23e1fae1a163dc 100644 --- a/server/server.js +++ b/server/server.js @@ -5,6 +5,16 @@ const pino = require('pino'); const swaggerJSDoc = require('swagger-jsdoc'); const axios = require('axios'); +// Read local data if needed +const fs = require('fs'); +const data = JSON.parse(fs.readFileSync('data.json', 'utf8')); + +function getRandomInt(min, max) { + min = Math.ceil(min); + max = Math.floor(max); + return Math.floor(Math.random() * (max - min)) + min; //The maximum is exclusive and the minimum is inclusive +} + // Define the logger const logger = pino({ prettyPrint: { @@ -124,15 +134,29 @@ app.get('/:width/:height', async (req, res) => { } // else, get random infos, put it in DB and serve it else { - const getName = await axios.get('https://namey.muffinlabs.com/name.json'); - const getFact = await axios.get('https://catfact.ninja/fact'); + let name; + let fact; + if (process.env.LOCAL === "true") { + logger.debug('local data'); + name = data.names[getRandomInt(0, data.names.length)]; + fact = data.facts[getRandomInt(0, data.facts.length)]; + } + else { + logger.debug('distant data'); + getName = await axios.get('https://namey.muffinlabs.com/name.json'); + getFact = await axios.get('https://catfact.ninja/fact'); + name = getName.data[0]; + fact = getFact.data.fact; + } + const kitten = { - name: getName.data[0], - fact: getFact.data.fact, + name: name, + fact: fact, image_url: 'https://placekitten.com/' + req.params.width + '/' + req.params.height, width: req.params.width, height: req.params.height } + if (useDb) { logger.debug('insert in DB', kitten); collection.insert(kitten); @@ -141,13 +165,16 @@ app.get('/:width/:height', async (req, res) => { } } catch (error) { logger.error(error) - res.status(500).send(error); + res.status(500).send(error); } }); // To catch unknow routes -app.use((_, res) => res.status(404).json({ code: 404, message: 'Route not found'})); +app.use((_, res) => { + logger.debug('Route not found'); + res.status(404).json({ code: 404, message: 'Route not found'}) +}); -app.listen(process.env.PORT, +app.listen(process.env.PORT, () => logger.info(`Server listening on port ${process.env.PORT}, env ${process.env.NODE_ENV}`) ); diff --git a/web/index.html b/web/index.html index f64eaac6d68709bb06aaa3da3a15f71b9d78cf8b..70cf2f0c021e36517467d3b9dd84f340d535de30 100644 --- a/web/index.html +++ b/web/index.html @@ -21,7 +21,7 @@ <form action=""> <input type="number" name="width" id="width" value="500"> <input type="number" name="height" id="height" value="500"> - <input id="myButton" type="button" value="Clic !" onclick="getInput();"> + <input id="myButton" type="button" value="Click !" onclick="getInput();"> </form> </div> @@ -34,7 +34,7 @@ </div> <div class="row"> - <p>Fact : </p> + <p>Cat fact : </p> <p id="fact"></p> </div>