Conversation
Add an --id option to use a different field than 'id' as the unique identifier of items. It accepts a field name (applied to all resources) or a JSON file mapping resource names to id field names. Resolves the long-standing request in typicode#279.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
What
Adds an
--idoption to use a different field thanidas the unique identifier of items:--id post_idusespost_idas the id field for all resources--id ids.jsonuses a per-resource mapping from a JSON file, e.g.{ "posts": "post_id", "comments": "comment_id" }The same option is available through the JavaScript API:
createApp(db, { id }).Why
This has been requested since 2016 in #279 (50 comments). Today every resource is forced to use the
idfield, which makes json-server unusable with databases that use other primary key names.How it works
ServiceandNormalizedAdapterboth accept anIdOption(stringglobal field, orRecord<resource, field>per-resource mapping)findById,create,updateById,patchById,destroyById) and id normalization (numeric to string, auto-generation) use the resource's id field--idis not passedTests
src/service.test.ts: CRUD against per-resource and global custom id fieldssrc/app.test.ts: HTTP integration (GET/POST/DELETE) with a custom id fieldsrc/adapters/normalized-adapter.test.ts: id normalization with custom fields, no defaultidinjectionAll 141 tests pass,
tsc --noEmitandoxlintare clean.