Skip to content

Commit

Permalink
Add feature tags (lukePeavey#17)
Browse files Browse the repository at this point in the history
* Add function to jest to auto-refresh when test files changed.

* Add API for getting a quote by its ID.

* Change 'sample' folder to 'samples' and update gitignore and contributing files.

* Add web API for getting list of 'tags'.

* Remove duplicate web API in 'routes' for getting a quote by its ID.

* Rename 'samples' folder back to 'sample'.
  • Loading branch information
marekdano authored and lukePeavey committed Jan 28, 2020
1 parent 08002ac commit d8a2e1e
Show file tree
Hide file tree
Showing 10 changed files with 148 additions and 12 deletions.
4 changes: 2 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,8 @@

docs/
private/
data/
!data/samples
data/*
!data/sample

# misc
.DS_Store
Expand Down
35 changes: 28 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ https://api.quotable.io/quotes
{
// The number of quotes returned by this request
count: number,
// The total number or quotes matching this request
// The total number of quotes matching this request
totalCount: number
// The index of the last quote returned. When paginating through results,
// this value would be used as the `skip` parameter when requesting the next
Expand Down Expand Up @@ -118,12 +118,12 @@ https://api.quotable.io/authors
{
// The number of authors return by this request.
count: number,
// The total number or authors matching this request.
totalCount: number
// The total number of authors matching this request.
totalCount: number,
// The index of the last item returned. When paginating through results,
// this value would be used as the `skip` parameter when requesting the next
// "page" of results.
lastItemIndex: number
lastItemIndex: number,
// The array of authors
results: {_id: string, name: string, quoteCount: string}[]
}
Expand All @@ -136,7 +136,7 @@ Get all quotes a specific author
#### Request

```http
https://api.quotable.io/author/:id
https://api.quotable.io/authors/:id
```

#### Response
Expand All @@ -145,14 +145,35 @@ https://api.quotable.io/author/:id
{
_id: string,
// The author name
name: number,
name: string,
// The total number of quotes by this author
quoteCount: number
quoteCount: number,
// The array of quotes by this author
quotes: {_id: string, content: string, author: string}[]
}
```

### Get Tags

Get list of available tags

#### Request

```http
https://api.quotable.io/tags
```

#### Response

```ts
{
// The number of all tags by this request
count: number,
// The array of tags
results: {_id: string, name: string}[]
}
```

## Usage

**Get a random quote (fetch)**
Expand Down
8 changes: 8 additions & 0 deletions __tests__/integration.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -84,3 +84,11 @@ describe('GET /quotes/:id', () => {
expect(response.type).toBe('application/json')
})
})

describe('GET /tags', () => {
it('Request completed successfully', async () => {
const response = await request(app).get('/tags')
expect(response.status).toBe(200)
expect(response.type).toBe('application/json')
})
})
2 changes: 1 addition & 1 deletion contributing.md
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ $ npm run install
This will populate your database with the sample data included in the repository.

```shell
$ npm run database:seed
$ npm run database:seed data/sample
```

**4. Start the Server**
Expand Down
58 changes: 58 additions & 0 deletions data/sample/tags.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
[
{
"_id": "lmOF86Cv",
"name": "famous-quotes"
},
{
"_id": "7HjmNmOIE",
"name": "life"
},
{
"_id": "ZY0PgehL1",
"name": "friendship"
},
{
"_id": "rYJgbbjOK",
"name": "science"
},
{
"_id": "ZBOfkMBWc",
"name": "technology"
},
{
"_id": "M97I8NOsF",
"name": "inspirational"
},
{
"_id": "PnbpDlRlC",
"name": "motivational"
},
{
"_id": "637eDKoGB",
"name": "literature"
},
{
"_id": "fqgdQmYNk",
"name": "art"
},
{
"_id": "BPCApygPx",
"name": "business"
},
{
"_id": "CkRvna8Tz",
"name": "love"
},
{
"_id": "AK9UKVnIm",
"name": "success"
},
{
"_id": "GADjjdrcd",
"name": "religion"
},
{
"_id": "8mV7Dhqt3",
"name": "social-justice"
}
]
15 changes: 14 additions & 1 deletion scripts/seedDatabase.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ const fs = require('fs')
const path = require('path')
const Quotes = require('../src/models/Quotes')
const Authors = require('../src/models/Authors')
const Tags = require('../src/models/Tags')

// Seeds the database with data from `quotes.json` and `authors.json`.
// This should be run when setting up a new database, or after modifying
Expand All @@ -17,6 +18,7 @@ console.log('==> Seeding database...')
const [dataDirectory] = process.argv.slice(2)
let _quotes
let _authors
let _tags

try {
_quotes = fs.readFileSync(
Expand All @@ -25,6 +27,9 @@ try {
_authors = fs.readFileSync(
path.join(__dirname, '../', dataDirectory, 'authors.json')
)
_tags = fs.readFileSync(
path.join(__dirname, '../', dataDirectory, 'tags.json')
)
} catch (error) {
console.log('==> [ERROR] Invalid data directory')
process.exit()
Expand All @@ -46,10 +51,18 @@ async function seedAuthors() {
console.log(`==> Added ${result.insertedCount} documents to Authors`)
}

async function seedTags() {
// Remove any existing data from the collection
await Tags.collection.deleteMany({})
// Import the items from authors.json
const result = await Tags.collection.insertMany(JSON.parse(_tags))
console.log(`==> Added ${result.insertedCount} documents to Tags`)
}

mongoose
.connect(process.env.MONGODB_URI, { useNewUrlParser: true })
.then(() => {
Promise.all([seedQuotes(), seedAuthors()]).then(() => {
Promise.all([seedQuotes(), seedAuthors(), seedTags()]).then(() => {
console.log('==> Finished!')
process.exit()
})
Expand Down
17 changes: 17 additions & 0 deletions src/controllers/tags/listTags.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
const Tags = require('../../models/Tags')

/**
* Get list of tags from the database.
*/
module.exports = async function listTags(req, res, next) {
try {
const results = await Tags.find({}).select('name')

res.status(200).json({
count: results.length,
results,
})
} catch (error) {
return next(error)
}
}
12 changes: 12 additions & 0 deletions src/models/Tags.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
const { Schema, model } = require('mongoose')
const shortid = require('shortid')

const TagSchema = new Schema({
_id: { type: String, default: shortid.generate },
name: { type: String, required: true },
})

// To support full text search
TagSchema.index({ name: 'text' })

module.exports = model('Tag', TagSchema)
3 changes: 2 additions & 1 deletion src/models/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const Quotes = require('./Quotes')
const Authors = require('./Authors')
const Tags = require('./Tags')

module.exports = { Quotes, Authors }
module.exports = { Quotes, Authors, Tags }
6 changes: 6 additions & 0 deletions src/routes.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ const getQuoteById = require('./controllers/quotes/getQuoteById')
const randomQuote = require('./controllers/quotes/randomQuote')
const listAuthors = require('./controllers/authors/listAuthors')
const getAuthorById = require('./controllers/authors/getAuthorById')
const listTags = require('./controllers/tags/listTags')

const router = Router()

Expand All @@ -20,4 +21,9 @@ router.get('/random', randomQuote)
router.get('/authors', listAuthors)
router.get('/authors/:id', getAuthorById)

/**------------------------------------------------
** Tags
**-----------------------------------------------*/
router.get('/tags', listTags)

module.exports = router

0 comments on commit d8a2e1e

Please sign in to comment.