2019-06-20 00:20:09 +02:00
|
|
|
import { generateId } from '../utils/GeneratorHelpers'
|
2018-12-17 15:54:58 +01:00
|
|
|
|
2019-06-20 00:20:09 +02:00
|
|
|
const prefix = 'did:op:'
|
2018-12-17 15:54:58 +01:00
|
|
|
|
2019-01-09 16:17:23 +01:00
|
|
|
/**
|
|
|
|
* Decentralized ID.
|
|
|
|
*/
|
2018-12-17 15:54:58 +01:00
|
|
|
export default class DID {
|
2019-01-09 16:17:23 +01:00
|
|
|
/**
|
|
|
|
* Parses a DID from a string.
|
|
|
|
* @param {string} didString DID in string.
|
|
|
|
* @return {DID}
|
|
|
|
*/
|
2019-07-16 14:56:56 +02:00
|
|
|
public static parse(didString: string | DID): DID {
|
|
|
|
if (didString instanceof DID) {
|
|
|
|
didString = didString.getDid()
|
|
|
|
}
|
2018-12-17 15:54:58 +01:00
|
|
|
let did: DID
|
2019-01-22 14:14:49 +01:00
|
|
|
const didMatch = didString.match(/^did:op:([a-f0-9]{64})$/i)
|
2019-01-22 14:18:58 +01:00
|
|
|
|
2019-01-22 14:14:49 +01:00
|
|
|
if (didMatch) {
|
|
|
|
did = new DID(didMatch[1])
|
2018-12-17 15:54:58 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
if (!did) {
|
|
|
|
throw new Error(`Parsing DID failed, ${didString}`)
|
|
|
|
}
|
|
|
|
|
|
|
|
return did
|
|
|
|
}
|
|
|
|
|
2019-01-09 16:17:23 +01:00
|
|
|
/**
|
|
|
|
* Returns a new DID.
|
|
|
|
* @return {DID}
|
|
|
|
*/
|
2018-12-17 15:54:58 +01:00
|
|
|
public static generate(): DID {
|
2019-02-14 12:37:52 +01:00
|
|
|
return new DID(generateId())
|
2018-12-17 15:54:58 +01:00
|
|
|
}
|
|
|
|
|
2019-01-09 16:17:23 +01:00
|
|
|
/**
|
|
|
|
* ID.
|
|
|
|
* @type {string}
|
|
|
|
*/
|
2018-12-17 15:54:58 +01:00
|
|
|
private id: string
|
|
|
|
|
|
|
|
private constructor(id: string) {
|
|
|
|
this.id = id
|
|
|
|
}
|
|
|
|
|
2019-01-09 16:17:23 +01:00
|
|
|
/**
|
|
|
|
* Returns the DID.
|
|
|
|
* @return {string}
|
|
|
|
*/
|
2018-12-17 15:54:58 +01:00
|
|
|
public getDid(): string {
|
|
|
|
return `${prefix}${this.id}`
|
|
|
|
}
|
|
|
|
|
2019-01-09 16:17:23 +01:00
|
|
|
/**
|
|
|
|
* Returns the ID.
|
|
|
|
* @return {string}
|
|
|
|
*/
|
2018-12-17 15:54:58 +01:00
|
|
|
public getId(): string {
|
|
|
|
return this.id
|
|
|
|
}
|
|
|
|
}
|