Skip to content

Instantly share code, notes, and snippets.

@4skinSkywalker
Last active October 20, 2019 02:55
Show Gist options
  • Save 4skinSkywalker/6fea6d3d5ec16f26dd1ea1e45ba5fff9 to your computer and use it in GitHub Desktop.
Save 4skinSkywalker/6fea6d3d5ec16f26dd1ea1e45ba5fff9 to your computer and use it in GitHub Desktop.
import { InMemoryDbService } from 'angular-in-memory-web-api'
import { RequestInfo } from 'angular-in-memory-web-api/interfaces'
export class MyInMemoryService implements InMemoryDbService {
createDb() {
// same as before
}
// HTTP POST interceptor
post(reqInfo: RequestInfo) {
// if client pinged api/authentication
// then call authenticate (defined below)
if (reqInfo.collectionName === 'authentication')
return this.authenticate(reqInfo)
// otherwise default response of In-memory DB
return undefined
}
// mocking authentication happens here
// HTTP POST interceptor handler
private authenticate(reqInfo: RequestInfo) {
// return an Observable response
return reqInfo.utils.createResponse$(() => {
console.log('HTTP POST api/authentication override')
const { headers, url, req } = reqInfo
// if request username and passord are correct
// return response with a JSONWebToken
const { username, password } = req['body']
if (username === 'fred92' && password === '1234')
return {
status: 200,
headers, // reqInfo (line 30)
url, // reqInfo (line 30)
body: {
token: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c'
}
}
// otherwise return response with status code 401 (unauthorized)
return {
status: 401,
headers,
url,
body: { }
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment