在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:ethanresnick/json-api开源软件地址:https://github.com/ethanresnick/json-api开源编程语言:TypeScript 96.8%开源软件介绍:json-apiThis library creates a JSON API-compliant REST API from your Node app and automatically generates API documentation. It currently integrates with Express or Koa apps that use Mongoose models, but it can easily be integrated with other frameworks and databases. If you want to see an integration with another stack, just open an issue! This library implements all the required portions of the 1.0 spec, which is more than enough for basic CRUD. It does not yet implement some of the smaller, optional pieces, like related resource URIs. V3 Installation
Example APICheck out the full, working v3 example repo for all the details on building an API with this library. Or, take a look at the basic example below: var app = require('express')()
, API = require('json-api');
var models = {
"Person": require('./models/person'),
"Place": require('./models/place')
};
var adapter = new API.dbAdapters.Mongoose(models);
var registry = new API.ResourceTypeRegistry({
"people": {
beforeRender: function(resource, req, res) {
if(!userIsAdmin(req)) resource.removeAttr("password");
return resource;
}
},
"places": {}
}, {
"dbAdapter": adapter,
"urlTemplates": {
"self": "/{type}/{id}"
}
});
// Tell the lib the host name our API is served from; needed for security.
const opts = { host: 'example.com' };
// Set up a front controller, passing it controllers that'll be used
// to handle requests for API resources and for the auto-generated docs.
var Front = new API.httpStrategies.Express(
new API.controllers.API(registry),
new API.controllers.Documentation(registry, {name: 'Example API'}),
opts
);
// Render the docs at /
app.get("/", Front.docsRequest);
// Add routes for basic list, read, create, update, delete operations
app.get("/:type(people|places)", Front.apiRequest);
app.get("/:type(people|places)/:id", Front.apiRequest);
app.post("/:type(people|places)", Front.apiRequest);
app.patch("/:type(people|places)/:id", Front.apiRequest);
app.delete("/:type(people|places)/:id", Front.apiRequest);
// Add routes for adding to, removing from, or updating resource relationships
app.post("/:type(people|places)/:id/relationships/:relationship", Front.apiRequest);
app.patch("/:type(people|places)/:id/relationships/:relationship", Front.apiRequest);
app.delete("/:type(people|places)/:id/relationships/:relationship", Front.apiRequest);
app.listen(3000); Core ConceptsResource Type DescriptionsThe JSON-API spec is built around the idea of typed resource collections. For example, you can have a To use this library, you describe the special behavior (if any) that resources of each type should have, and then register those descriptions with a central
Query FactoriesWhen a request comes in, the json-api library extracts various parameters from it to build a query that will be used to fulfill the user's request. However, to support advanced use cases, you might want to override how the library generates this query in order to select/update different data, or to modify how the query's result (data or error) is placed into the JSON:API response. To do this, you can just pass in your own function (a "query factory") for constructing this query. See an example here. One simple thing you can do with query factories is to create urls (or, in REST terminology, resources) that map to different database items over time. For example, you could have an Query factory functions are also a good place to do permissions checks that rely on access to the parsed request body. If the user doesn't have permission, you can throw an error, and the library will pass it along gracefully in the response. See error handling. FilteringThis library supports filtering out of the box, using a syntax that's designed to be easier to read, easier to write, and more expressive than the square bracket syntax used by libraries like qs. For example, to include only items where the zip code is either 90210 or 10012, you'd write:
By contrast, with the square-bracket syntax, you'd have to write something like:
Also, the square-bracket syntax can't represent empty arrays or distinguish between non-string literals (e.g. Formatting filtering constraintsIn this library's default format, the value of the
The value can be a number, The valid operators (for the buit-in Mongoose adapter) are: If you have multiple constraints, you can choose whether to combine them with an
Will find all the people who are named Bob or who live in the 90210 zip code. Filter constraints listed next to each other at the top-level are combined with an "AND". E.g., The Putting it all together, you could do:
This will find everyone born after 1963 who also has either the name "Test" or the email "[email protected]". Note: your API can use a totally different filter query parameter format if you so desire, by providing a custom parser (see example). Also, each adapter can indicate support for a custom set of operators. On URL EncodingWhen sending filter constraints, make sure you don't URL encode characters that the syntax above uses as delimiters (namely, commas, parentheses, backticks, square brackets, and the exclamation point), unless you mean for these characters to be interpreted as part of your data (e.g., part of a field name or value) rather than as a separator. Be aware that some clients, by default, automatically percent-encode certain characters in url query strings -- especially the backtick and square brackets. This will cause the server to error, because it won't see the appropriate (unescaped) delimiter characters. Whether the client is correct to do this automatic encoding is a nuanced question, as there are competing and conflicting standards governing URLs today (namely, RFC 3986 and WHATWG Url). If you encounter this problem, check your client for a way to make requests without any automatic encoding. If your client absolutely insists on URL encoding backticks (the trickiest character), you can delimit your strings with exclamation points ( PaginationPagination limit and offset parameters are accepted in the following form:
For example, to get 25 people starting at the 51st person:
Error HandlingCode that you provide the library (e.g., a query factory function) can throw an error or, in some cases, return a promise that rejects with an error. Any time an If you want to pass information about the error back to the user, you need to explicitly mark it as safe to expose to the user, which you can do in two ways. First, you can throw an instance of the library's Many errors are also serialized by the library with standard URIs in their Routing, Authentication & ControllersThis library gives you a Front controller (shown in the example) that can handle requests for API results or for the documentation. But the library doesn't prescribe how requests get to this controller. This allows you to use any url scheme, routing layer, or authentication system you already have in place. You just need to make sure that: The library may, in the future, also read In the example above, routing is handled with Express's built-in Database AdaptersAn adapter handles all the interaction with the database. It is responsible for turning requests into standard |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论