Skip to content

create base structure #327

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -114,3 +114,5 @@ dist
.yarn/build-state.yml
.yarn/install-state.gz
.pnp.*

.vscode
67 changes: 67 additions & 0 deletions api/recipes/recipes-module.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
// function getRecipeById(recipe_id){
// return Promise.resolve('awesome')
// }
//以上 Promise.resolve()是用于检测function是否启用
const db=require('./../../data/db.config')

async function getRecipeById(recipe_id){
const rows= await db("recipes as r").leftJoin('steps as s', 'r.recipe_id','s.recipe_id')
.leftJoin('step_ingredients as si', 'si.step_id','s.step_id')
.leftJoin('ingredients as i','si.ingredient_id','i.ingredient_id')
.select(
'r.recipe_id',
'r.recipe_name',
's.step_id',
's.step_number',
's.step_instructions',
'si.quantity',
'i.ingredient_id',
'i.ingredient_name'
)
.where('r.recipe_id', recipe_id)
.orderBy('s.step_number')

const recipes={
recipe_id: rows[0].recipe_id,
recipe_name: rows[0].recipe_name,
steps:rows.reduce((acc,row)=>{
if (!row.ingredient_id){
return acc.concat({
step_id: row.step_id,
step_number: row.step_number,
step_instructions:row.step_instructions,
ingredients: []
})
}
if(row.ingredient_id && !acc.find(step=>step.step_id===row.step_id)){
return acc.concat({
step_id: row.step_id,
step_number: row.step_number,
step_instructions: row.step_instructions,
ingredients: [
{
ingredient_id: row.ingredient_id,
ingredient_name: row.ingredient_name,
quantity: row.quantity
}
]
})
}
const currentStep=acc.find(step=>step.step_id===row.step_id)
currentStep.ingredients.push({

ingredient_id: row.ingredient_id,
ingredient_name: row.ingredient_name,
quantity: row.quantity

})
return acc

},[])
}
return recipes
}

module.exports={
getRecipeById
}
36 changes: 36 additions & 0 deletions api/recipes/recipes-router.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
const express = require('express')
const router = express.Router()
const Recipe=require('./recipes-module')

router.get('/:recipe_id',(req,res,next)=>{
Recipe.getRecipeById(req.params.recipe_id)
.then(resource=>{
//throw new Error("wrong !!")
res.status(200).json(resource)
})
.catch(next)
})















router.use((err, req, res, next) => { // eslint-disable-line
res.status(err.status || 500).json({
sageAdvice: 'something went wrong inside the recipes router',
message: err.message,
stack: err.stack,
})
})

module.exports = router
14 changes: 14 additions & 0 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
const express = require('express');

const recipesRouter = require('./recipes/recipes-router');

const server = express();

server.use(express.json());

server.use('/api/recipes', recipesRouter);
server.use("*", (req, res, next) => { // eslint-disable-line
res.json({ api: 'up' })
})

module.exports = server;
5 changes: 5 additions & 0 deletions data/db.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const knex=require('knex')
const configurations=require('../knexfile')
const environment=process.env.NODE_ENV||'development'

module.exports=knex(configurations[environment])
51 changes: 51 additions & 0 deletions data/migrations/20230907213618_first-migration.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.up = async function(knex) {
await knex.schema.createTable('recipes',tbl=>{
tbl.increments('recipe_id');
tbl.string('recipe_name',128).notNullable().unique();
// tbl.string('created_at').notNullable()
})
.createTable('ingredients', tbl => {
tbl.increments("ingredient_id");
tbl.string('ingredient_name', 200).notNullable().unique();
tbl.string('ingredient_unit',50)


})
.createTable('steps',tbl=>{
tbl.increments("step_id");
tbl.integer('step_number').notNullable().unsigned();
tbl.string('step_instructions',255).notNullable();
tbl.integer('recipe_id').unsigned().notNullable()
.references('recipe_id').inTable('recipes')
.onDelete('RESTRICT').onUpdate("RESTRICT")
})
.createTable('step_ingredients', tbl => {
tbl.increments("step_ingredient_id");
tbl.float('quantity', 128).notNullable();
tbl.integer('step_id').unsigned().notNullable()
.references('step_id').inTable('steps')
.onDelete('RESTRICT').onUpdate("RESTRICT")
tbl.integer('ingredient_id').unsigned().notNullable()
.references('ingredient_id').inTable('ingredients')
.onDelete('RESTRICT').onUpdate("RESTRICT")
})


};

/**
* @param { import("knex").Knex } knex
* @returns { Promise<void> }
*/
exports.down = async function(knex) {
await knex.schema
.dropTableIfExists('step_ingredients')
.dropTableIfExists('steps')
.dropTableIfExists('ingredients')
.dropTableIfExists('recipes')

};
Binary file added data/recipe.db3
Binary file not shown.
8 changes: 8 additions & 0 deletions data/seeds/01-cleanup.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
const cleaner = require('knex-cleaner');

exports.seed = function (knex) {
return cleaner.clean(knex, {
mode:'truncate',
ignoreTables: ['knex_migrations', 'knex_migrations_lock'],
});
};
51 changes: 51 additions & 0 deletions data/seeds/02-make-recipes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
const recipes=[
{recipe_name:'Broccoli Pesto Pasta'},
{ recipe_name: 'Lemon Chicken' },
{ recipe_name: 'Salmon en Papillote' },
]

const ingredients=[
{ingredient_name:'Broccoli',ingredient_unit:'lbs'},
{ ingredient_name: 'Pesto', ingredient_unit: 'lbs' },
{ ingredient_name: 'Pasta', ingredient_unit: 'lbs' },
{ ingredient_name: 'Lemon', ingredient_unit: 'slices' },
{ ingredient_name: 'Chicken', ingredient_unit: 'kilos' },
{ ingredient_name: 'Salmon', ingredient_unit: 'grams' }
]

const steps=[
//Broccoli Pesto Pasta
{step_instructions:"Heat pan",step_number:1,recipe_id:1},
{ step_instructions: "Add broccoli", step_number: 2, recipe_id: 1 },
{ step_instructions: "Add pesto mixed with pasta", step_number: 3, recipe_id: 1 },
//Lemon Chicken
{ step_instructions: "Heat oven", step_number: 1, recipe_id: 2},
{ step_instructions: "Put chicken and lemon in oven", step_number: 2, recipe_id: 2 },
{ step_instructions: "Put in oven at 500 degrees", step_number: 3, recipe_id: 2 },
//Salmon en Papillote
{ step_instructions: "Fish a salmon in the Bidasoa river", step_number: 1, recipe_id: 3 },
{ step_instructions: "Cook salmon", step_number: 2, recipe_id: 3 }
]

const step_ingredients=[
//Broccoli Pesto Pasta
{ step_id: 2, ingredient_id: 1, quantity:1},
{ step_id: 3, ingredient_id: 2, quantity: 1.5 },
{ step_id: 3, ingredient_id: 3, quantity: 2 },
//Lemon Chicken
{ step_id: 5, ingredient_id: 4, quantity: 1 },
{ step_id: 5, ingredient_id: 5, quantity: 0.4 },
//Salmon en Papillote
{ step_id: 7, ingredient_id: 6, quantity: 1 }


]


exports.seed = async function (knex) {
await knex('recipes').insert(recipes)
await knex('ingredients').insert(ingredients)
await knex('steps').insert(steps)
await knex('step_ingredients').insert(step_ingredients)

};
6 changes: 6 additions & 0 deletions index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
require('dotenv').config()
const server=require('./api/server.js')

const port=process.env.PORT || 9001

server.listen(port,()=>console.log(`\nAPI running on port ${port}\n`))
24 changes: 24 additions & 0 deletions knexfile.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Update with your config settings.

/**
* @type { Object.<string, import("knex").Knex.Config> }
*/
const sharedConfig={
client: 'sqlite3',
migrations: { directory: './data/migrations'},
seeds: {directory: './data/seeds'},
useNullAsDefault: true,
pool: { afterCreate: (conn, done) => { conn.run('PRAGMA foreign_keys = ON', done)}}
}
module.exports = {

development: {
...sharedConfig,
connection: {filename: './data/recipe.db3'}
},
testing:{
...sharedConfig,
connection: { filename: './data/cook_book.test.db3' }
}

};
Loading