init commit

This commit is contained in:
Vic 2022-04-19 16:47:00 +02:00
commit 014483aff0
9 changed files with 291 additions and 0 deletions

1
CODEOWNERS Normal file
View File

@ -0,0 +1 @@
* @udacity/active-public-content

46
LICENSE.txt Normal file
View File

@ -0,0 +1,46 @@
Copyright © 2012 - 2020, Udacity, Inc.
Udacity hereby grants you a license in and to the Educational Content, including
but not limited to homework assignments, programming assignments, code samples,
and other educational materials and tools (as further described in the Udacity
Terms of Use), subject to, as modified herein, the terms and conditions of the
Creative Commons Attribution-NonCommercial- NoDerivs 3.0 License located at
http://creativecommons.org/licenses/by-nc-nd/4.0 and successor locations for
such license (the "CC License") provided that, in each case, the Educational
Content is specifically marked as being subject to the CC License.
Udacity expressly defines the following as falling outside the definition of
"non-commercial":
(a) the sale or rental of (i) any part of the Educational Content, (ii) any
derivative works based at least in part on the Educational Content, or (iii)
any collective work that includes any part of the Educational Content;
(b) the sale of access or a link to any part of the Educational Content without
first obtaining informed consent from the buyer (that the buyer is aware
that the Educational Content, or such part thereof, is available at the
Website free of charge);
(c) providing training, support, or editorial services that use or reference the
Educational Content in exchange for a fee;
(d) the sale of advertisements, sponsorships, or promotions placed on the
Educational Content, or any part thereof, or the sale of advertisements,
sponsorships, or promotions on any website or blog containing any part of
the Educational Material, including without limitation any "pop-up
advertisements";
(e) the use of Educational Content by a college, university, school, or other
educational institution for instruction where tuition is charged; and
(f) the use of Educational Content by a for-profit corporation or non-profit
entity for internal professional development or training.
THE SERVICES AND ONLINE COURSES (INCLUDING ANY CONTENT) ARE PROVIDED "AS IS" AND
"AS AVAILABLE" WITH NO REPRESENTATIONS OR WARRANTIES OF ANY KIND, EITHER
EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. YOU
ASSUME TOTAL RESPONSIBILITY AND THE ENTIRE RISK FOR YOUR USE OF THE SERVICES,
ONLINE COURSES, AND CONTENT. WITHOUT LIMITING THE FOREGOING, WE DO NOT WARRANT
THAT (A) THE SERVICES, WEBSITES, CONTENT, OR THE ONLINE COURSES WILL MEET YOUR
REQUIREMENTS OR EXPECTATIONS OR ACHIEVE THE INTENDED PURPOSES, (B) THE WEBSITES
OR THE ONLINE COURSES WILL NOT EXPERIENCE OUTAGES OR OTHERWISE BE UNINTERRUPTED,
TIMELY, SECURE OR ERROR-FREE, (C) THE INFORMATION OR CONTENT OBTAINED THROUGH
THE SERVICES, SUCH AS CHAT ROOM SERVICES, WILL BE ACCURATE, COMPLETE, CURRENT,
ERROR- FREE, COMPLETELY SECURE OR RELIABLE, OR (D) THAT DEFECTS IN OR ON THE
SERVICES OR CONTENT WILL BE CORRECTED. YOU ASSUME ALL RISK OF PERSONAL INJURY,
INCLUDING DEATH AND DAMAGE TO PERSONAL PROPERTY, SUSTAINED FROM USE OF SERVICES.

54
README.md Normal file
View File

@ -0,0 +1,54 @@
# Storefront Backend Project
## Getting Started
This repo contains a basic Node and Express app to get you started in constructing an API. To get started, clone this repo and run `yarn` in your terminal at the project root.
## Required Technologies
Your application must make use of the following libraries:
- Postgres for the database
- Node/Express for the application logic
- dotenv from npm for managing environment variables
- db-migrate from npm for migrations
- jsonwebtoken from npm for working with JWTs
- jasmine from npm for testing
## Steps to Completion
### 1. Plan to Meet Requirements
In this repo there is a `REQUIREMENTS.md` document which outlines what this API needs to supply for the frontend, as well as the agreed upon data shapes to be passed between front and backend. This is much like a document you might come across in real life when building or extending an API.
Your first task is to read the requirements and update the document with the following:
- Determine the RESTful route for each endpoint listed. Add the RESTful route and HTTP verb to the document so that the frontend developer can begin to build their fetch requests.
**Example**: A SHOW route: 'blogs/:id' [GET]
- Design the Postgres database tables based off the data shape requirements. Add to the requirements document the database tables and columns being sure to mark foreign keys.
**Example**: You can format this however you like but these types of information should be provided
Table: Books (id:varchar, title:varchar, author:varchar, published_year:varchar, publisher_id:string[foreign key to publishers table], pages:number)
**NOTE** It is important to remember that there might not be a one to one ratio between data shapes and database tables. Data shapes only outline the structure of objects being passed between frontend and API, the database may need multiple tables to store a single shape.
### 2. DB Creation and Migrations
Now that you have the structure of the databse outlined, it is time to create the database and migrations. Add the npm packages dotenv and db-migrate that we used in the course and setup your Postgres database. If you get stuck, you can always revisit the database lesson for a reminder.
You must also ensure that any sensitive information is hashed with bcrypt. If any passwords are found in plain text in your application it will not pass.
### 3. Models
Create the models for each database table. The methods in each model should map to the endpoints in `REQUIREMENTS.md`. Remember that these models should all have test suites and mocks.
### 4. Express Handlers
Set up the Express handlers to route incoming requests to the correct model method. Make sure that the endpoints you create match up with the enpoints listed in `REQUIREMENTS.md`. Endpoints must have tests and be CORS enabled.
### 5. JWTs
Add JWT functionality as shown in the course. Make sure that JWTs are required for the routes listed in `REQUIUREMENTS.md`.
### 6. QA and `README.md`
Before submitting, make sure that your project is complete with a `README.md`. Your `README.md` must include instructions for setting up and running your project including how you setup, run, and connect to your database.
Before submitting your project, spin it up and test each endpoint. If each one responds with data that matches the data shapes from the `REQUIREMENTS.md`, it is ready for submission!

42
REQUIREMENTS.md Normal file
View File

@ -0,0 +1,42 @@
# API Requirements
The company stakeholders want to create an online storefront to showcase their great product ideas. Users need to be able to browse an index of all products, see the specifics of a single product, and add products to an order that they can view in a cart page. You have been tasked with building the API that will support this application, and your coworker is building the frontend.
These are the notes from a meeting with the frontend developer that describe what endpoints the API needs to supply, as well as data shapes the frontend and backend have agreed meet the requirements of the application.
## API Endpoints
#### Products
- Index
- Show
- Create [token required]
- [OPTIONAL] Top 5 most popular products
- [OPTIONAL] Products by category (args: product category)
#### Users
- Index [token required]
- Show [token required]
- Create N[token required]
#### Orders
- Current Order by user (args: user id)[token required]
- [OPTIONAL] Completed Orders by user (args: user id)[token required]
## Data Shapes
#### Product
- id
- name
- price
- [OPTIONAL] category
#### User
- id
- firstName
- lastName
- password
#### Orders
- id
- id of each product in the order
- quantity of each product in the order
- user_id
- status of order (active or complete)

14
docker-compose.yml Normal file
View File

@ -0,0 +1,14 @@
version: '3.9'
services:
postgres:
image: postgres
ports:
- '5432:5432'
env_file:
- .env
volumes:
- 'postgres:/var/lib/postgresql/data'
volumes:
postgres:

30
package.json Normal file
View File

@ -0,0 +1,30 @@
{
"name": "storefront_backend",
"version": "0.1.0",
"description": "",
"main": "server.ts",
"scripts": {
"start": "node src/server.ts",
"watch": "tsc-watch --esModuleInterop src/server.ts --outDir ./dist --onSuccess \"node ./dist/server.js\"",
"test": "jasmine-ts",
"tsc": "tsc"
},
"author": "Udacity",
"license": "ISC",
"dependencies": {
"express": "^4.17.1",
"body-parser": "^1.19.0",
"typescript": "^4.1.3",
"pg": "^8.5.1"
},
"devDependencies": {
"@types/express": "^4.17.9",
"@types/jasmine": "^3.6.3",
"@types/pg": "^7.14.7",
"jasmine": "^3.6.4",
"jasmine-spec-reporter": "^6.0.0",
"jasmine-ts": "^0.3.0",
"ts-node": "^9.1.1",
"tsc-watch": "^4.2.9"
}
}

19
spec/support/jasmine.json Normal file
View File

@ -0,0 +1,19 @@
{
"spec_dir": "spec",
"spec_files": [
"../**/tests/*[s]pec.ts"
],
"helpers": [
"helpers/**/*.js"
],
"reporters": [
{
"name": "jasmine-spec-reporter#SpecReporter",
"options": {
"displayStacktrace": "all"
}
}
],
"stopSpecOnExpectationFailure": false,
"random": true
}

15
src/server.ts Normal file
View File

@ -0,0 +1,15 @@
import express, { Request, Response } from 'express'
import bodyParser from 'body-parser'
const app: express.Application = express()
const address: string = "0.0.0.0:3000"
app.use(bodyParser.json())
app.get('/', function (req: Request, res: Response) {
res.send('Hello World!')
})
app.listen(3000, function () {
console.log(`starting app on: ${address}`)
})

70
tsconfig.json Normal file
View File

@ -0,0 +1,70 @@
{
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "ES2020", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
"lib": ["es2015", "dom"], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
"rootDir": "./src", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
// "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUncheckedIndexedAccess": true, /* Include 'undefined' in index signature results */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}